Enums in C#

Enums in C# with Examples

In this article, I am going to discuss Enums in C# with examples. Please read our previous article where we discussed Indexers in C# in detail. At the end of this article, you will understand what are Enums in C# and when and how to use Enums in C# with some examples.

Why do we need Enums in C#?

The Enums are strongly typed names constants. Let’s understand enums with an example. I have an Employee class with the Name and Gender properties. Gender is an integer. 

  1. 0 is an Unknown gender
  2. 1 is Male
  3. 2 is Female
The complete example is given below
using System;
using System.Collections.Generic;

namespace EnumsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a collection to store employees
            List<Employee> empList = new List<Employee>();
            empList.Add(new Employee() { Name = "Anurag", Gender = 0});
            empList.Add(new Employee() { Name = "Pranaya", Gender = 1 });
            empList.Add(new Employee() { Name = "Priyanka", Gender = 2 });
            empList.Add(new Employee() { Name = "Sambit", Gender = 3 });
            
            //Loop through each employees and print the Name and Gender
            foreach (var emp in empList)
            {
                Console.WriteLine("Name = {0} && Gender = {1}", emp.Name, GetGender(emp.Gender));
            }

            Console.ReadLine();
        }

        //This method is used to return the Gender 
        public static string GetGender(int gender)
        {
            // The switch here is less readable because of these integral numbers
            switch (gender)
            {
                case 0:
                    return "Unknown";
                case 1:
                    return "Male";
                case 2:
                    return "Female";
                default:
                    return "Invalid Data for Gender";
            }
        }
    }

    // 0 - Unknown
    // 1 - Male
    // 2 - Female
    public class Employee
    {
        public string Name { get; set; }
        public int Gender { get; set; }
    }
}

When we run the program we get the output as expected as shown below.

Enums in C#

The downside of the above program is less readable as well as less maintainable. This is because it operates on integrals instead of using enums to get the gender.

Now let’s see how to replace these integral numbers with enums to makes the program more readable and maintainable.

First, create an enum for the Gender as shown below.

Enums in C#

Then modify the GetGender method as shown below to enums.

Enums in C#

Here in the above, we are using Enums instead of integer integrals which make the code more readable and maintainable.

The complete example is given below
using System;
using System.Collections.Generic;

namespace EnumsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a collection to store employees
            List<Employee> empList = new List<Employee>();
            empList.Add(new Employee() { Name = "Anurag", Gender = 0});
            empList.Add(new Employee() { Name = "Pranaya", Gender = 1 });
            empList.Add(new Employee() { Name = "Priyanka", Gender = 2 });
            empList.Add(new Employee() { Name = "Sambit", Gender = 3 });
            
            //Loop through each employees and print the Name and Gender
            foreach (var emp in empList)
            {
                Console.WriteLine("Name = {0} && Gender = {1}", emp.Name, GetGender(emp.Gender));
            }

            Console.ReadLine();
        }

        //This method is used to return the Gender 
        public static string GetGender(int gender)
        {
            // The switch here is now more readable and maintainable because 
            // of replacing the integral numbers with Gender enum
            switch (gender)
            {
                case (int)Gender.Unknown:
                    return "Unknown";
                case (int)Gender.Male:
                    return "Male";
                case (int)Gender.Female:
                    return "Female";
                default:
                    return "Invalid Data for Gender";
            }
        }
    }

    // 0 - Unknown
    // 1 - Male
    // 2 - Female
    public class Employee
    {
        public string Name { get; set; }
        public int Gender { get; set; }
    }

    public enum Gender
    {
        Unknown,
        Male,
        Female
    }
}

Now when you run the application you will get the output as expected as shown below.

Enums in C#

So, if a program uses a set of integral numbers then consider them replacing with enums which makes the program more Readable and Maintainable.

Points to Remember about C# Enums:
  1. The Enums are enumerations.
  2. Enums are strongly typed named constants. Hence, an explicit cast is needed to convert from the enum type to an integral type and vice versa. Also, an enum of one type cannot be implicitly assigned to an enum of another type even though the underlying value of their members is the same.
  3. The default underlying type of an enum is int.
  4. The default value for the first element of the enum is ZERO and gets incremented by 1.
  5. It is also possible to customize the underlying type and values of enums.
  6. The Enums are value types.
  7. Enum keyword (all small letters) is used to create the enumerations, whereas the Enum class, contains static GetValues() and GetNames() methods which can be used to list Enum underlying type values and Names.
Default underlying type is int and the value starts at ZERO

Enums in C#

The Gender enum underlying type is now short and the value starts from and incremented by 1

Enums in C#

So, in this case, the value for Male is 2 and for Female the value is 3.The Enum values need not to be in sequential order. Any valid underlying type value is allowed 

Enums in C#

The following enum will not be compiled, because the maximum value allowed for the short data type is 32767. 

Enums in C#

Note: Use short.MaxValue to find out the maximum value that a short data type can hold

An explicit cast is needed to convert from enum type to an integral type and vice versa.

int i = Gender.Male;

The above line will not compile. A compiler error will be generated stating: Cannot implicitly convert type ‘Gender’ to ‘int’. An explicit conversion exists (are you missing a cast?)

Gender female = 2; 

The above line will also not compile. A slightly different compiler error will be generated stating: The left-hand side of an assignment must be a variable, property or indexer

Enum of one type cannot be implicitly assigned to an enum of another type

The Enum of one type cannot be implicitly assigned to an enum of another type even though the underlying value of their members are same. In such cases, an explicit cast is required as shown in the below example

namespace EnumsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // This following line will not compile. 
            // Cannot implicitly convert type 'Season' to 'Gender'. 
            // An explicit conversion is required.
            // Gender gender = Season.Winter;

            // The following line comiples as we have an explicit cast
            Gender gender = (Gender)Season.Winter;
        }
    }

    public enum Gender : int
    {
        Unknown = 1,
        Male = 2,
        Female = 3
    }
    public enum Season : int
    {
        Winter = 1,
        Spring = 2,
        Summer = 3
    }
}
Understanding GetValues() and GetNames() methods

The enum keyowrd (all small letteres) in C# is used to create enumerations whereas the Enum class in C# contains the static GetValues() and GetNames() methods which can be used to list the Enum underlying type values and Names. Let us understand this with an example.

namespace EnumsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] Values = (int[])Enum.GetValues(typeof(Gender));
            Console.WriteLine("Gender Enum Values");
            foreach (int value in Values)
            {
                Console.WriteLine(value);
            }

            Console.WriteLine();
            string[] Names = Enum.GetNames(typeof(Gender));
            Console.WriteLine("Gender Enum Names");
            foreach (string Name in Names)
            {
                Console.WriteLine(Name);
            }
       Console.ReadKey();
        }
    }

    public enum Gender : int
    {
        Unknown = 1,
        Male = 2,
        Female = 3
    }
}

When we run the application, it gives us the following output.

nderstanding GetValues() and GetNames() methods of Enum in C#

The Enums cannot be derived from other enums.

Let us understand this with an example. Here we have two enums InitialDays and Weekdays and we are trying to inherit the WeekDays enums from the InitialDays enum as shown in the below image.

Understanding Enums in C#

When we compile the application, it gives us the below error.

The Enums cannot be derived from other enums

So, we cannot derive enums from another enum. Well, if enums cannot be derived from enums then can be a class derived from enums? Let’s find it out with an example.

using System;
namespace EnumsDemo
{
    class Program : WeekDays
    {
        static void Main(string[] args)
        {
            Console.WriteLine((int)WeekDays.Monday);
            Console.WriteLine((int)WeekDays.Sunday);
            Console.WriteLine((int)WeekDays.Tuesday);
            Console.WriteLine((int)WeekDays.Wednesday);
            Console.WriteLine((int)WeekDays.Thursday);
            Console.WriteLine((int)WeekDays.Friday);
            Console.WriteLine((int)WeekDays.Saturday);
            
            Console.ReadKey();
        }
    }
    
    public enum WeekDays
    {
        Sunday,
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday
    }
}

When we compile the application, it gives us the following error.

Why we cannot derive enums from another enum

The above error states that classes cannot be derived from enums. This is because Enums are treated as sealed classes and hence all rules that are applicable to sealed classes also apply to enums.

Duplicate Enum Members:

Let us try to create two enum members with the same name as shown in the below example.

using System;
namespace EnumsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine((int)Gender.Unknown);
            Console.WriteLine((int)Gender.Male);
            Console.WriteLine((int)Gender.Female);           
            Console.ReadKey();
        }
    }
    
    public enum Gender
    {
        Unknown,
        Male,
        Female,
        Unknown
    }
}

When we compile the program, it gives us the following error.

Duplicate Enum Members

The Enums are like classes, so we cannot define two members with the same name.

In the next article, I am going to discuss Enums with Mathematical Operations in C#. Here, in this article, I try to explain Enums in C# with examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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