Pages

Men

rh

6/16/2012

Enums in C#

Enum:
  • Enums are basically a set of named constants.
  • They are declared in C# using the enum keyword.
  • Every enum type automatically derives from System.Enum and thus we can use System.Enum methods on our Enums.
  • Enums are value types and are created on the stack and not on the heap. You don't have to use new to create an enum type.
  • Declaring an enum is a little like setting the members of an array as shown below.
Example:
        
       enum Rating {Poor, Average, Okay, Good, Excellent}
You can pass enums to member functions just as if they were normal objects. And you can perform arithmetic on enums too.

For example we can write two functions, one to increment our enum and the other to decrement our enum.

Example
               Rating IncrementRating(Rating r)
               {
                   if(r == Rating.Excellent)
                       return r;
                   else
                       return r+1;
               }
Rating DecrementRating(Rating r)
{
    if(r == Rating.Poor)
        return r;
    else
        return r-1;
}

Where to use enums 

Quite often we have situations where a class method takes as an argument a custom option.

Let's say we have some kind of file access class and there is a file open method that has a parameter that 
might be one of read-mode, write-mode, read-write-mode, create-mode and append-mode.

Now you might think of adding five static member fields to your class for these modes. Wrong approach!
 
Declare and use an enumeration which is a whole lot more efficient and is better programming practice in my opinion.

No comments :

Post a Comment