Enumerations (Enum) basics.

An enumeration is a collection of constants. Instead of defining a static class and adding public constants, we have a much cleaner and nicer syntax that provides some benefits:

enum MyEnumeration
{
    None = 0,
    First = 1,
    Second = 2,
    Last = 100
}

This defines an enumeration of integers. We can simply access them by using MyEnumeration.None,MyEnumeration.Last or others. By default an enumeration is of integer type, however, this can be changed by using the inheritance operator : like in the following example.

enum AnotherEnumeration : byte
{
    Zero,
    One,
    Two,
    Eleven = 11,
    Twelve
}

What is the value of each constant here? The C# compiler determines that automatically. In this caseZero would be 0, One would be 1 and Two would be 2. Since we tell the compiler to set Eleven to 11, it will automatically set Twelve to be 12. Also each value is of the byte type.

There are big advantages of using enumerations instead of plain constants or integers. Enumerations are strongly typed and have an improved string representation using the ToString method. Also using an enumeration as a parameter for a method is strongly encouraged as compared to a plain integer or a similar type. The advantage is that any other programmer is able to see which values are valid and what they basically stand for.

Advertisements
By Sriramjithendra Posted in C#.NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s