Home > Software engineering >  How to convert any int into any generic Enum in C#?
How to convert any int into any generic Enum in C#?

Time:11-30

Because Enums aren't guaranteed to be of type int...

public enum ExampleEnum : int / ulong / whatever

You cannot do this with enums:

int i = (int)exampleEnum;

However in my case, while I don't know the exact 'type of enum' being used, I can guarantee that it will be a "int type" of enum.

So I can do this:

int i = Convert.ToInt32(exampleEnum);

Cool. Here's the problem: I don't know of a way to do the inverse (which I need to do), as:

Enum exampleEnum = (Enum)exampleEnum;

has error:

Cannot cast expression of type 'int' to type 'Enum'

And I cannot find an inverse of Convert.ToInt32(Enum enum)


That is the question, if you think more detail on what I'm trying to do is useful, I can provide you with it. But in a nutshell I am creating a generic GUI method that takes in any type of Enum:

public static int EditorPrefEnumField(string label, Enum defaultValue, string editorPrefString)

and getting it to work (the way I want) involves converting the Enum to and from an int.

CodePudding user response:

You can use Enum.ToObject() method. You need to specify the actual enum type for that. Here is a generic method to encapsulate Enum.ToObject()

public enum TestEnum : int 
{
    A=1, B=2, C=3
};

public T GetEnumFromInt<T>(int value) where T : Enum
{
    return (T)Enum.ToObject(typeof(T), value);
}

private void button1_Click(object sender, EventArgs e) 
{
    Enum value = GetEnumFromInt<TestEnum>(2);
    MessageBox.Show(value.ToString()); // Displays "B" 
}

You need to specify the concrete type of Enum you want because Enum is an abstract type and one cannot create instances of abstract types.

CodePudding user response:

Take this code where I store an error code as an Int:

public class CommonError
{
   public int Code { get; set; }

   public CommonError FromErrorCode(Enum code, string description = "")
   {
        Code = (int)Enum.Parse(code.GetType(), code.ToString());                        
        return this;
   }
}

Yet what I'm doing when I call it is parsing in different Enums:

new CommonError().FromErrorCode((int)GeneralErrorCodes.SYSTEM_BASE_ERROR);

Cool. Here's the problem: I don't know of a way to do the inverse (which I need to do)

To do the reverse of this you need the Enum Type, eg:

Enum.GetNames(typeof(AnEmumType))

Enum.GetValues(typeof(AnEmumType)).ToList();
  • Related