Wednesday, February 22, 2012

Enumerations

Recall my previous post about value types vs. reference types. Just to recap, simple data types such as int, float, double, decimal etc. are value types while complex types such as objects, strings are reference types. There are two exceptions to this concept. Structures and Enumerations. Despite being complex types, Structures and Enumerators are value types and hence they are stored on stack as opposed to heap.

In this post we will discuss enumerations and we will cover structures in next post.

Enumerations
Enumerations allow you to group constants at one place in a name-value pair format and allows you to access the values using strongly typed names. The key difference between an array list or a dictionary object and enumeration is that the arraylist / dictionary is a reference type and hence stored on heap while enumerators are value types and are stored on stack. Use of enumerators also allow you to keep the constants at one place hence being able to easily manage them and makes your code easier to read.

The underlying datatype for an enumeration can only be of an integral type. It can be of any integral type except "Char". The default type is int.

An enumeration is declared using enum keyword. Lets see an example.

enum Color
{
   Red,
   Blue,
   Green,
   Orange
}

If you don't specify the value, underlying integer datatype is assumed and the value is assigned from 0 onwards. For example in above example, Red=0, Blue=1, Green=2, Orange=3.

You can explicitly assign any value to each type, for example

enum Color
{
   Red = 8,
   Blue = 9,
   Green  =12,
   Orange=20
}


As I mentioned previously, underlying datatype for an enum can be any integral type except char. Following datatypes are supported 
  • byte, sbyte, short, ushort, int, uint, long or ulong.
To use any other datatype except int, declare it as follows...


enum Color : byte
{
   Red ,
   Blue ,
   Green ,
   Orange
}

Usage
Apart from keeping the constants at one place, it also makes code easier to read. See the following example...

 public class EnumTest
 {
   static void Main()
   {
      Console.WriteLine("Red={0}", Color.Red);
      Console.WriteLine("Blue={0}", Color.Blue);
   }
}

That's all there is to it. It is a relatively simple concept but when used appropriately promotes cleaner and readable code.

Thank you.

No comments:

Post a Comment