Enums In C#

“The great power comes with a great responsibility.”
 
Enums are basically a set of named constants. They are declared in C# using the keyword enum. Every enum type automatically derives from System.Enum namespace 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 keyword to create an enum type. Declaring an enum is the members of an array as given below.
 
enum Rating {Poor, Average, Okay, Good, Excellent}
 
You can pass enums to member functions just as they are normal objects. And you can perform arithmetic operations on enums too. For example we can write two functions, one to increment our enum and the other to decrement our enum.
 
Rating IncrementEnum(Rating r)
{
    if(r == Rating.Excellent)
        return r;
    else
        return r+1;
}
Rating DecrementEnum(Rating r)
{
    if(r == Rating.Poor)
        return r;
    else
        return r-1;
}
 
Both functions take a Rating object as argument and return back a Rating object. Now we can call these functions from anywhere.
 
for (Rating r1 = Rating.Poor; 
r1 < Rating.Excellent;
r1 = IncrementEnum(r1))
{           
    Console.WriteLine(r1);
}

Console.WriteLine();

for (Rating r2 = Rating.Excellent; 
    r2 > Rating.Poor; 
    r2 = DecrementEnum (r2))
{
    Console.WriteLine(r2);          
}
 
And here is a sample code showing, how you can call System.Enum methods on our Enum object. We call the GetNames method which retrieves an array of the names of the constants in the enumeration.
 
foreach(string s in Rating.GetNames(typeof(Rating)))
Console.WriteLine(s);