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.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - C# Integer

  • C# Convert Int to String
  • Random Int in C#
  • Random Number in a Range in C#
  • Related Article - C# Enum

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