C# Enum – Massive Guide on C# Enumerations

Enum is a keyword in C# that is used to declare an Enumeration. Enumerations also known as Enums are special sets of named values which generally correspond to a set of constants. Enums are helpful when you have to declare a set of constants and each one of the constants corresponds to a number.

Enums make the program design modular and reduce the bug insertion rate. Enums are strongly typed constants and can be used with intellisense in Visual Studio. The beauty of an Enum is that – it makes easier for you to modify its values in the future, in addition to this they also help to reduce the errors caused by making typo mistakes or mistyping numbers.

C# Enum

How MSDN Defines an Enum:

An Enum is a, “distinct type that consists of a set of named constants called the enumerator list.”

Syntax:

enum <enum_name>
{
	<element 1>,
	<element 2>,
	<element 3>
}

Example 1 – Code Snippet of working with an Enum in C#:

Below is an example on how to use Enums in C#:

enum Month
{
    January = 1,
    February,
    March,
    April,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December
}

class Program
{
    static void Main(string[] args)
    {
       Console.WriteLine("The {0}rd Month is {1}", (int)Month.March, Month.March);
   
       Console.ReadKey();
    }
}
Output:
The 3rd Month is March

Explaining the Example 1 code snippet:

Line 1 to Line 15: From line 1 to 15 we have declared an Enum with the name ‘Month’. This enum contains the name of months and their sequential order (i.e. month number).

Note: It should be noted that for assigning the sequence numbers to months, we have just assigned a number to the first month i.e. ‘January = 1′. This helps the enum to understand that the first element does not correspond to 0 but to 1. And it assigns a number to the following elements by incrementing 1 to the value of the previous element, provided you have not defined them. So, in this example the value of January will be 1, for February it will be 2 and similarly for December it will be 12.

Line 21: On line 21, there is a ‘Console.WriteLine’ statement that takes ‘(int)Month.March’  and ‘Month.March’  as arguments. The argument ‘(int)Month.March’  gives you the value of the specified enum element. And argument ‘Month.March’ gives you the name of the specified enum constant.

Example 2 – Another Code Snippet of working with an Enum in C#:

In this example, we will see a program that gets a month number from the user and displays its name on the console.

Note: Please note that there are many other better ways to write a program for the above scenario but here we are writing this program just in order to understand enums.

namespace Enum_Example
{
    enum Month
    {
        Invalid,
        January,
        February,
        March,
        April,
        May,
        June,
        July,
        August,
        September,
        October,
        November,
        December
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the month number: ");

            int monthNumber = -1;
            int.TryParse(Console.ReadLine(), out monthNumber);

            switch (monthNumber)
            {
                case (int)Month.January:
                    Console.WriteLine("This is " + Month.January);
                    break;

                case (int)Month.February:
                    Console.WriteLine("This is " + Month.February);
                    break;

                case (int)Month.March:
                    Console.WriteLine("This is " + Month.March);
                    break;

                case (int)Month.April:
                    Console.WriteLine("This is " + Month.April);
                    break;

                case (int)Month.June:
                    Console.WriteLine("This is " + Month.June);
                    break;

                case (int)Month.July:
                    Console.WriteLine("This is " + Month.July);
                    break;

                case (int)Month.August:
                    Console.WriteLine("This is " + Month.August);
                    break;

                case (int)Month.September:
                    Console.WriteLine("This is " + Month.September);
                    break;

                case (int)Month.October:
                    Console.WriteLine("This is " + Month.October);
                    break;

                case (int)Month.November:
                    Console.WriteLine("This is " + Month.November);
                    break;

                case (int)Month.December:
                    Console.WriteLine("This is " + Month.December);
                    break;

                case (int)Month.Invalid:
                    Console.WriteLine("Invalid Month");
                    break;
            }

            Console.ReadKey();
        }
    }
}
Output:
Enum-Example-2-Resultant

Explaining the Example 2 code snippet:

Line 3 to Line 18: From lines 3 to 18, we have defined an enum with the name ‘Month’ same as we have done in the Example 1.

Note: Notice that in this case we haven’t assigned any number specifically to the first enum element, so it will have a default value 0, and the next element will have a value 1 and so on.

Line 27: On Line 27, we have accepted the user input by ‘Console.ReadLine()’ statement and stored it in a variable named as ‘monthNumber’.

Line 29: On line 29, we have supplied the ‘monthNumber’ variable to the switch statement. If you don’t know how a switch statement works, then for the time being you can simple assume it to work as a statement that passes the control to the case block whose value is equal to the value supplied to the switch.

So, now if user enters 11 it passes the control to the case block where the value evaluates to 11 i.e. on Line 68 as ‘(int)Month.November’ is equal to 11 and hence it prints the result as – ‘This is November’

Few Important Points about C# Enumerations:

Below are few important points about C# Enums:

  1. The underlying value of an Enum element is an Int. So, in context to the above examples when you write ‘Month.January’ it’s actually an int with value 1.
  2. An enum is a form of syntactic sugar that makes your programs cleaner, easier to read and less prone errors caused by invalid constants. In addition to this, it also causes no slowdown at runtime.
  3. You cannot cast an enum element to string, but you can cast it to int. For example: writing ‘(string)Month.January’ will give you a compile time error while ‘(int)Month.January’ gives you the corresponding month number for the element.
  4. To print the enum values, you can call ‘ToString()’ method on the enum element. Internally, ‘ToString()’ method invokes the methods that use reflection to acquire the string representation of an enum element. But it should be noted that ‘Console.WriteLine’ automatically calls the ‘ToString()’ method on all types passed to it, so there is no need to explicitly call the ‘ToString()’ inside ‘Console.WriteLine’.
  5. In order to make valid enums, always use the default value of zero, as we have shown in the Example 2 – by having an ‘Invalid’ element at the zeroth place. This can often be useful for verifying correctness of your code. In addition to this, FxCop (a code analysis tool from Microsoft) always gives you suggestion that “enums should have zero value” in case you have an enum that doesn’t have zeroth element.
  6. Enums are quite fast and almost never create a performance concern in your code.
  7. Enums are treated as sealed classes and like classes enums, cannot contain two members having the same name.

How to Iterate through an Enum in C#:

There are scenarios when you need to loop though an enum. Below is the code snippet that demonstrates how to do this:

namespace Enum_Example
{
    enum Month
    {
        January = 1,
        February,
        March,
        April,
        May,
        June,
        July,
        August,
        September,
        October,
        November,
        December
    }

    class Program
    {
        static void Main(string[] args)
        {
            //Iterating through an Enum to Get Element Names
            string[] months = Enum.GetNames(typeof(Month));
            foreach (string month in months)
            {
                Console.WriteLine(month);
            }
                
            Console.ReadKey();
        }
    }
}
Output:
January
February
March
April
May
June
July
August
September
October
November
December

Explaining the above code snippet:

In the above code snippet we have first declared an enum with the name ‘Month’. Then we have used the ‘GetNames()’ method of the Enum class. This method retrieves the array of the names of the constants in the specified enumeration. After this, we use have used a foreach loop to print each element on the screen.

Enum.GetNames Method:

The ‘GetNames’ is a static method implemented in ‘System.Enum’ class. This method takes the Enum type as input parameter and returns array of the names of the constants in a specified enumeration. For supplying the Enum type to the method you can make use of the ‘typeof’ operator.

The Enum.GetNames method internally accesses the metadata representation of the Enum in memory and then fetches the element names from that.

Another very useful method in the Enum class is ‘Enum.GetValues’.

Enum.Getvalues Method:

The ‘GetValues’ is again a static method implemented in ‘System.Enum’ class. This method also takes the Enum type as input parameter but unlike the ‘Enum.GetVaules’ method it returns an array of the values of the constants in a specified enumeration.

There is a difference between ‘Enum.GetNames’ and ‘Enum.GetValues’ and that is – the ‘System.Array’ returned by ‘GetValues’ implements ‘IList’ ,while the ‘string[]’ returned by GetNames does not implements ‘IList’.

So, while iterating if you want to fetch both the names and element values then this is the method to look for.

Below is a code snippet of how to use this method:

namespace Enum_Example
{
    enum Month
    {
        January = 1,
        February,
        March,
        April,
        May,
        June,
        July,
        August,
        September,
        October,
        November,
        December
    }

    class Program
    {
        static void Main(string[] args)
        {
            //Iterating through an Enum to Get Element Names and Values
            Array months = Enum.GetValues(typeof(Month));
            foreach (var month in months)
            {
                Console.WriteLine("Month number "+(int)month + " is "+ month);
            }      
          
            Console.ReadKey();
        }
    }
}
Output:
Month number 1 is January
Month number 2 is February
Month number 3 is March
Month number 4 is April
Month number 5 is May
Month number 6 is June
Month number 7 is July
Month number 8 is August
Month number 9 is September
Month number 10 is October
Month number 11 is November
Month number 12 is December

How to Check If an Item is present in an Enum or Not:

In certain cases, you need to check whether an element is defined inside an Enum or not. In such cases you can use the ‘Enum.IsDefined()’ method.

Enum.IsDefined Method:

IsDefined is a static method implemented inside the System.Enum class. This method returns a Boolean value as an indication whether a constant with a specified value exists in a particular enumeration or not.

‘Enum.IsDefined’ method takes two input parameters i.e. ‘enumType’ and the second one is the ‘Object’ that needs to be searched. Below is an example of how to use ‘IsDefined’ method in C#.

enum Month
{
    January = 1,
    February,
    March,
    April,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December
}

class Program
{
    static void Main(string[] args)
    {
        //Check whether January is defined in the Month Enum
        if (Enum.IsDefined(typeof(Month), "January"))
        {
            Console.WriteLine("January is defined!");
        }
        else
        {
            Console.WriteLine("January is not defined!");
        }

        Console.ReadKey();
    }
}
Output:
January is defined!

C# Enums with Flag Attributes:

Flags allow an enum value to contain multiple values. An enum type with the [Flags] attribute can have many constant values assigned to it. The flags attribute should be used whenever the enumerator represents a collection of flags, rather than a single value. These collections are usually manipulated using bitwise operators.

Below is an example that can demonstrate this:

namespace Enum_Example
{
    //Normal Enum
    enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }
    
    //Enum with Flag Attribute
    [Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }

    class Program
    {
        static void Main(string[] args)
        {
            //This will result into a value "5"
            var str1 = (Suits.Spades | Suits.Diamonds).ToString();
            Console.WriteLine("Output of Normal Enum : "+str1);

            //This will result into two values i.e. "Spades, Diamonds"          
            var str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString();
            Console.WriteLine("Output of Enum With Flag Attribute : " + str2);
                       
            Console.ReadKey();

        }
    }
}
Output:
Output of Normal Enum : 5

Output of Enum With Flag Attribute : Spades, Diamonds

So, this was all about C# Enumerations. Hope you would find this tutorial useful. Happy Coding :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>