Converting an Integer to Enum in C#: A Comprehensive Guide

Category > CSHARP || Published on : Monday, March 13, 2023 || Views: 262 || C# enums integer conversion programming


This article explores the process of converting an integer value to an enum in C#. Enums are an important feature of C# that allow developers to define a set of related named constants. By understanding how to convert an integer to an enum, developers can make their code more robust and flexible.

When working with enumerated types in C#, there are times when you may need to convert an integer value to an enum. This can be a useful technique when you need to map an integer value to an enumerated type for processing or validation purposes. In this article, we will explore how to convert an int to an enum in C#.

What is an Enum in C#?

An enum is a value type in C# that represents a set of named constants. Enums are used to define a set of related named constants, which can be used to represent a specific range of values. Enums are useful when you want to create a limited set of values that can be used as input parameters or return values for a function.

Converting an int to an Enum in C#

To convert an integer value to an enum in C#, you can use the Enum.Parse() method. The Enum.Parse() method is a built-in method in C# that allows you to convert a string representation of an enum to an actual enum value.

Here's an example:

enum WeekDays
{
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6,
    Sunday = 7
}

class Program
{
    static void Main(string[] args)
    {
        int day = 3;
        WeekDays weekDay = (WeekDays)day;

        Console.WriteLine("Today is {0}", weekDay);
    }
}

In this example, we have defined an enum called WeekDays with seven named constants. We have assigned integer values to each named constant to represent the days of the week.

We then define a variable called day and set its value to 3. We then convert this integer value to an enum value by using the cast operator (WeekDays) to cast the integer value to the WeekDays enum.

Finally, we print the value of the weekDay variable to the console.

Conclusion

In this article, we have seen how to convert an int to an enum in C# using the Enum.Parse() method. Enums are a useful feature in C# that can be used to define a limited set of related named constants. By knowing how to convert an int to an enum, you can leverage this feature to create more robust and flexible code.