Is it possible to cast integer to enum? [duplicate]

Yes, it’s possible to cast Enum to int and vice versa, because every Enum is actually represented by an int per default. You should manually specify member values.
By default it starts from 0 to N.

It’s also possible to cast Enum to string and vice versa.

public enum MyEnum
{
    Value1 = 1,
    Value2 = 2,
    Value3 = 3
}

private static void Main(string[] args)
{
    int enumAsInt = (int)MyEnum.Value2; //enumAsInt == 2

    int myValueToCast = 3;
    string myValueAsString = "Value1";
    MyEnum myValueAsEnum = (MyEnum)myValueToCast;   // Will be Value3

    MyEnum myValueAsEnumFromString;
    if (Enum.TryParse<MyEnum>(myValueAsString, out myValueAsEnumFromString))
    {
        // Put logic here
        // myValueAsEnumFromString will be Value1
    }

    Console.ReadLine();
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)