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.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp Integer

  • Convert Int to Bool in C#
  • Convert Long to Integer in C#
  • Related Article - Csharp Enum

  • Random Number in a Range in C#
  • Convert Enum to String in C#