Cast integer to enum in C#

Enum values can be converted to integral values and vice versa using type casts. For example:

using System;
					
public class Program
{

    public enum ProgrammingLanguages
    {
        CSharp,
        PHP,
        Python,
        Java,
        Go,
        Javascript
    }
    
    public static void Main()
    {
        ProgrammingLanguages MyEnum1 = (ProgrammingLanguages) 2;
        Console.WriteLine(MyEnum1); // Python

        // Or

        ProgrammingLanguages MyEnum2 = (ProgrammingLanguages)Enum.ToObject(typeof(ProgrammingLanguages), 4);
        Console.WriteLine(MyEnum2); // GO
    }
    
}

Leave a Comment

Your email address will not be published. Required fields are marked *