Enums in C# (Part-1)

Enums in C#

In this article, I am going to discuss Enums in C# with examples. 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:
  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

In the next article, we will continue our discussion with enums with more different types of examples.

SUMMARY:

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 *