Monday 11 August 2014

Enum in C#

Enum:
An enumeration is a set of named integer constants. An enumerated type is declared using the enumkeyword.C# enumerations are value data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance.
Enumerations are special sets of named values which all maps to a set of numbers, usually integers. They come in handy when you wish to be able to choose between a set of constant values, and with each possible value relating to a number, they can be used in a wide range of situations. As you will see in our example, enumerations are defined above classes, inside our namespace. This means we can use enumerations from all classes within the same namespace.

Why we need enum :

Eg:

class Demo
{
public static void Main()
{
int Sunday = 0;
int Monday = 1;
int Tuesday = 2;
int Wednesday = 3;
int Thursday = 4;
int Friday = 5;
int Saturday = 6;
System.Console.WriteLine(Sunday);
System.Console.WriteLine(Monday);
System.Console.WriteLine(Tuesday);
System.Console.WriteLine(Wednesday);
System.Console.WriteLine(Thursday);
System.Console.WriteLine(Friday);
System.Console.WriteLine(Saturday);
}
}

output
0
1
2
3
4
5
6

The above program compiles and runs successfully to give the desired output. I am sure you must have realized how much efforts this requires; you had to put the "=" sign and the value next to every variable that identifies a weekday. C# provides a convinient way for carrying out this work and that's enums! So on to enums. We will use enums to write the above program.

enum WeekDays
{
   Sunday,
   Monday,
   Tuesday,
   Wednesday,
   Thursday,
   Friday,
   Saturday
}

class Demo
{
  public static void Main()
  {
      
            System.Console.WriteLine((int)WeekDays.Sunday);
            System.Console.WriteLine((int)WeekDays.Monday);
            System.Console.WriteLine((int)WeekDays.Tuesday);
            System.Console.WriteLine((int)WeekDays.Wednesday);
            System.Console.WriteLine((int)WeekDays.Thursday);
            System.Console.WriteLine((int)WeekDays.Friday);
            System.Console.WriteLine((int)WeekDays.Saturday);    
  }
}

output: 
0
1
2
3
4
5
6

No comments:

Post a Comment