How to Get an Enum from a Number in C#

By FoxLearn 1/16/2025 3:03:09 AM   38
To get an enum from a number in C#, you can use the Enum.ToObject method, which allows you to convert an integer value to its corresponding enum value.

In this tutorial, we'll learn how to convert an integer to an enum using a generic method.

This is useful when you need to convert numbers from various sources (e.g., files or network sockets) to enums. By using a generic method, you can handle conversions to any enum type with a single function, avoiding the need to cast return values for each specific enum.

public T NumToEnum<T>(int number)
{
    return (T)Enum.ToObject(typeof(T), number);
}

The Enum.ToObject() method does the heavy lifting by casting the integer to the enum type.

First, we’ll create a DaysOfWeek enum to represent the days of the week, and a MonthsInYear enum to represent the months in a year.

public enum DaysOfWeek
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

public enum MonthsInYear
{
    January,
    February,
    March,
    April,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December
}

Using the NumToEnum Function

Now, let’s see how to use the NumToEnum function to convert integer values to the appropriate enum values.

int day = 3;   // Represents Wednesday
int month = 10; // Represents October

// Convert the day number to the corresponding DayOfWeek enum value
DaysOfWeek d = NumToEnum<DaysOfWeek>(day);
// d is now DaysOfWeek.Wednesday

// Convert the month number to the corresponding MonthsInYear enum value
MonthsInYear m = NumToEnum<MonthsInYear>(month);
// m is now MonthsInYear.October

In the above code, we pass integer values (3 and 10) to the NumToEnum function. For day, the function returns DaysOfWeek.Wednesday, and for month, it returns MonthsInYear.October.

Why Use a Generic Function?

Instead of writing separate conversion methods for each enum type, the generic NumToEnum function allows you to convert integers to any enum, all with the same function.

By using a generic method like NumToEnum, you can handle conversions for different enum types without repeating yourself.