Convert Int to Enum in C#

Minahil Noor Mar 09, 2021
Convert Int to Enum in C#

This article will introduce a method to convert an int to enum in C#.

Use the Type Casting to Convert an Int to Enum in C#

We will use the traditional typecasting to cast an int to enum in C#. An enum is a special class that represents a group of constants, unchangeable, and read-only variables. The correct syntax to use type casting is as follows.

YourEnum variableName = (YourEnum)yourInt;

The program below shows how we can use the type casting to cast an int to enum in C#.

using System;
public class Program {
    public enum MyEnum
{
    Zero = 0,
    One = 1
}
   public static void Main() {
int val = 1;
MyEnum num = (MyEnum)val;
Console.WriteLine(num);
   }
}

Output:

One

We have cast our integer value to enum constant One.

Related Article - Csharp Integer

Related Article - Csharp Enum