TechieClues TechieClues
Updated date Aug 19, 2022
In this blog, we will learn how to convert int to enum and vise-versa using C#.
  • 1.9k
  • 0
  • 0

In this blog, we will see how to convert an int to an enum and from an enum to an int using C#.

What is int?

int is a keyword that is used to declare a variable that can store an integral type of value (signed integer) the range from -2,147,483,648 to 2,147,483,647. It is an alias of the System.Int32.

What is Enum?

An enum is a special value type that enables a variable to be a set of predefined constants. To define an enumeration type, we can use the enum the keyword as shown below,

enum Colour
{
    Red,
    Blue,
    Green,
    Pink,
    White
}

How to convert int to an enum in C#?

If we don’t want to lose information during conversion, we will use explicit conversion complier require that you perform conversion of data type which is called a cast.

 In this example, we will explicitly cast an int to the enum as shown below,

Colour colour1, colour2, colour3;
// Casting to enum from an int
colour1 = (Colour)2;
colour2 = (Colour)4;
colour3 = (Colour)1;

How to convert an enum to int in C#?

In this example, we will explicitly cast an enum to int as shown below,

// Cating to int from an enum
int colorCode1 = (int)Colour.Red;
int colorCode2 = (int)Colour.White;
int colorCode3 = (int)Colour.Green;

Code Snippet:

using System;
namespace StreamWriterSample
{
    class Program
    {
        // Define Enum
        enum Colour
        {
            Red = 1,
            Blue = 2,
            Green = 3,
            Pink = 4 ,
            White = 5
        }
        static void Main(string[] args)
        {                       
            // Casting to enum from an int
            Colour colour1 = (Colour)2;
            Colour colour2 = (Colour)4;            
            Colour colour3 = (Colour)1;
            // Print values
            Console.WriteLine("Cast int to enum:");
            Console.WriteLine(colour1);
            Console.WriteLine(colour2);
            Console.WriteLine(colour3);

            // Cating to int from an enum
            int colorCode1 = (int)Colour.Red;
            int colorCode2 = (int)Colour.White;
            int colorCode3 = (int)Colour.Green;
            // Print values
            Console.WriteLine("Cast enum to int:");
            Console.WriteLine(colorCode1);
            Console.WriteLine(colorCode2);
            Console.WriteLine(colorCode3);
            Console.ReadKey();
        }
    }
}

Output: 

Cast int to enum:
Blue
Pink
Red
Cast enum to int:
1
5
3

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!