Monday 28 November 2011

C# Enum


A C# enum (enumeration) is a user-defined integer TYPE. When we declare an enum in C# we have to supply a set of acceptable values (integers) that the instances of the enum type can hold. We have the freedom of naming those given values to make it more developer friendly. You will appreciate the real power of a C# enum from the fact that when, somewhere in your code, you attempt to assign an illegal value to an enum type, the code does not compile.

We benefit from a C# enum in a number of ways. Enums make our code more readable and, therefore, easier to maintain. With enums we no longer need to use those “magic” numbers in our code, we replace those magic numbers by descriptive names. Enums make our code easier to type, too. Whenever we need to supply a value to an enum type, the Visual Studio.NET’s IntelliSense helps us by providing a list of acceptable values to choose from.


We can define an enumeration as follows:

public enum DaysOfWeek
{
Friday = 0,
Saturday = 1,
Sunday = 2,
Monday = 3,
Tuesday = 4,
Wednesday = 5,
Thursday = 6
}

In the above DaysOfWeek enum type , we assign an integer value to represent each day of the week. To access the DaysOfWeek enum we use the ‘.’ notation. For example to DaysOfWeek.Friday would return the value 0 and DaysOfWeek.Thursday would return the integer value 6.

We can retrieve the string representation of an elements of an enum by calling the ToString() method. For example the following line of code would print Friday on the console:

Console.WriteLine(DaysOfWeek.Friday.ToString());

One more fact worth appreciating is that behind the curtains C# enums are instantiated as structs. To recall, the structs are value types and unlike reference types, that are created on the heap area of memory, they are created on the stack, as do ints, floats and chars etc., and are faster than the reference types. All the enums in C# are derived from the base class System.Enum.

No comments:

Post a Comment