C# enum

C# enum makes an application more readable and more maintainable. The C# enum is a keyword which allows us to declare an enumeration. It's better to use an enum if an application is using a set of integral numbers to apply some sort of logic. Let's understand this with an example.

Example

Try It
using System;
 
namespace TutorialsLeader
{
    public class MyFirstClass
    {
        public static void Main()
        {
            Student[] students = new Student[4];
 
            students[0] = new Student() { Name = "Jhon", Gender = 1 };
            students[1] = new Student() { Name = "Rob", Gender = 1 };
            students[2] = new Student() { Name = "Rebecca", Gender = 2 };
            students[3] = new Student() { Name = "Stefen", Gender = 3 };
 
            foreach (var student in students)
            {
                Console.WriteLine("Student name is : {0} and gender is {1}", student.Name, GetGender(student.Gender));
            }
        }
 
        static string GetGender(int gender)
        {
            switch (gender)
            {
                case 1:
                    return "Male";
                case 2:
                    return "Female";
                case 3:
                    return "Unknown";
                default:
                    return "Invalid selection";
            }
        }
    }
 
    public class Student
    {
        public string Name { get; set; }
        public int Gender { get; set; }
    }
}

In the above example, Student class is being used as a custom datatype to store the Name and Gender of users. As you can see the Gender type is an integer. In this case, one can not predict the Gender by looking at integer number until he/she reads the documentation of the application. This is the situation where enums play an important role to make your application more readable and maintainable.

Let's create the same program with an enum.

Example

Try It
using System;
 
namespace TutorialsLeader
{
    public class MyFirstClass
    {
        static void Main(string[] args)
        {
            Student[] students = new Student[4];
            students[0] = new Student() { Name = "Jhon", Gender = Gender.Male };
            students[1] = new Student() { Name = "Rob", Gender = Gender.Male };
            students[2] = new Student() { Name = "Json", Gender = Gender.Female };
            students[3] = new Student() { Name = "Rebecca", Gender = Gender.Unknown };
 
 
            foreach (var student in students)
            {
                Console.WriteLine("Student name is {0} and student gender is :{1}", student.Name, getGender(student.Gender));
            }
        }
 
 
        static string getGender(Gender gender)
        {
            switch (gender)
            {
                case Gender.Male:
                    return "Male";
                case Gender.Female:
                    return "Female";
                case Gender.Unknown:
                    return "Unknown";
                default:
                    return "Invalid Input";
            }
        }
 
    }
 
    public class Student
    {
        public string Name { get; set; }
        public Gender Gender { get; set; }
    }
 
    public enum Gender
    {
        Male = 1,
        Female = 2,
        Unknown = 3
    }
}

In the very first example, you have seen that to store the gender information of a student an integer type was being used. But just by looking at the integer number it was not possible to know the gender of a student, on the other hand, as you can see in the above example a Gender enum is being used to store the gender information of a student. Which makes very easy to know the gender of a student.

In the above example, a switch method has been used to get the Gender name. This method is operating on the Gender enum, and just by looking at the labels of enum it has become very easy to apply logic and return the result.

So from both the examples above it's very clear that enums make the applications more readable and maintainable.

Default Type

The default underlying type of an enum is integer. The default value for the first element is zero and gets incremented by 1 automatically. But this is possible to change the default underlying type of an enum and the values contained by the enum members.

Let's understand this with an example :

Example

Try It
public enum WeekDayName
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}
public class MyFirstClass
{
    public static void Main()
    {
        Console.WriteLine((int)WeekDayName.Monday);
        Console.WriteLine((int)WeekDayName.Tuesday);
        Console.WriteLine((int)WeekDayName.Wednesday);
        Console.WriteLine((int)WeekDayName.Thursday);
    }
}
Output

0

1

2

3

As you can the above example is print the values from 0 to 3 which is in increamenting order. If any change happens in the value of first member of an enum, the runtime automatically increments the values of each member by 1 in sequence. Let's understand this with an example.

Example

Try It
public enum WeekDayName
{
    Monday = 10,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}
Console.WriteLine((int)WeekDayName.Monday);
Console.WriteLine((int)WeekDayName.Tuesday);
Console.WriteLine((int)WeekDayName.Wednesday);
Console.WriteLine((int)WeekDayName.Thursday);
Output

10

11

12

13

Enums are strongly typed constants. This is why an explicit cast is required to convert from enum type to an integral type and vice versa. Also, it is not possible to assign the value of an enum to another enum implicitly. Even though the underlying value of their members are same.

int num = (int)WeekDayName.Monday; //Explicit casting

In the following example Although the underlying datatype for both enums are integer, but it is not possible to assign the value implicitly. Following statement throw an error.

WeekDayName day;
day = Gender.Male; //Cannot implicitly convert type Gender to WeekDayName. An explicit conversion exists (are you missing a cast?)

After type casting the statement becomes valid.

day = (WeekDayName)Gender.Male; //Valid

It is also possible to change the default underlying type of an enum, Following is an example which demonstrates that how we can change the underlying type.

Example

Try It
enum Gender : short // Default underlying type changed to short
{
    Male,
    Female,
    Other
}
Console.WriteLine((int)Gender.Male);
Console.WriteLine((int)Gender.Female);
Console.WriteLine((int)Gender.Other);

It's important to remember that enum(all small) and Enum both are different. enum is the keyword used to create enumerations whereas the Enum is a class which contains different methods, using them we can do manipulations on an enum.

Enum Important Methods

Method Uses
string GetName Retrieves the name of the constant in the specified enumeration that has the specified value.
string[] GetNames Retrieves an array of the names of the constants in a specified enumeration.
Array GetValues Retrieves an array of the values of the constants in a specified enumeration.
object Parse Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
object ToObject It has several overloaded methods used to convert the unsigned/signed integer to an enumeration member.

Let's learn about partial class in the next section.