Enumeration in c#

nkpandey 878 views 7 slides Feb 12, 2019
Slide 1
Slide 1 of 7
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7

About This Presentation

Enumeration in c#


Slide Content

Enumeration in C# Dr. Neeraj Kumar Pandey

Enumeration An enumeration is a user defined integer type which provides a way for attaching names to numbers. The enum keyword automatically enumerates a list of words by assigning them values 0,1,2…. enum shape { Circle, Square, Triangle } This can be written as:- enum shape{ Circle,Square,Triangle } Here ,Circle has the value 0,Square has the value 1 and Triangle has the value 2.

Enumeration Program class EnumTest { public static void Main() { Area area= new Area(); area.AreaShape (15,Area.Shape.Circle); area.AreaShape (15,Area.Shape.Square); area.AreaShape (15,( Area.Shape )1); area.AreaShape (15,( Area.Shape ) 10); } } using System; class Area { public enum Shape { Circle, Square } public void AreaShape ( int x, Shape shape) { double area; switch(shape) { case Shape.Circle : area= Math.PI *x*x; Console.WriteLine("Circle Area="+area); break; case Shape.Square : area=x*x; Console.WriteLine("Square Area="+area); break; default: Console.WriteLine("Invalid Input"); break; } } }

Enumeration Initialization Default value of the first enum member is 0 and that of each subsequent is incremented by one. We can assign specific values for different members. enum color { Red=4, Green=Red+3, Black=Red+Green+2, Yellow=5 } enum color { Red=4, Green=9 , Black=3, Yellow=5 }

Enumeration Initialization If the declaration of an enum member has no initializer, then its value is set implicitly as follows:- If it is the first member, its value is zero. Otherwise, its value is obtained by adding one to the value of the previous member. Consider the following enum declaration:- e num Alphabet { A, B=5, C, D=20, E } Following enum declaration is not valid because the declarations are circular enum ABC { A, B=C, C }

Enumerator Base Type By default, the enum type is int. However, we can declare explicitly a base type for each enum. The valid base type for enum are:- byte,sbyte,short,ushort,int,uint,long and ulong . e num Position : byte { Off, On } e num shape: long { Circle, Square=100, Rectangle }

Enumerator Type Conversion Enum types can be converted to their base type and back again with an explicit conversion using a cast. Enum values { value0, value1, value2, value3 } values u1=(values) 1; int a= ( int )u1;