Matthew
Matthew

Reputation: 10444

Is there a typesafe enum conversion from int in c#?

I know that I can convert an int to an enum using a cast

MyEnumType myEnum = (MyEnumType) myInteger;

The problem here is that the runtime cast won't stop me at build time if myInteger is not of type int

void MyMethod(MyObject myObject)
{
    MyEnumType myEnum = (MyEnumType) myObject.someProperty;
    ....
}

The above is not an uncommon code pattern but it won't protect me at build-time if the object's property type has been changed.

Is there a built-in method to do this conversion that will give me a build-time error? I could, of course, write a generic method rather easily but I'm wondering if one is built in.

Upvotes: 3

Views: 208

Answers (2)

Marvin Smit
Marvin Smit

Reputation: 4108

You can use

Enum.TryParse(myInteger.ToString(), out result)

to get the Enum value of an int.

Hope this helps,

Upvotes: 2

Servy
Servy

Reputation: 203830

You can create a method to do this for your one enum easily enough:

public static MyEnumType CastFromInt<T>(int n)
{
    return (MyEnumType)n;
}

Sadly, because there is no way to apply a generic constraint such that a generic type argument is an enumeration, there's no good way to genericize this. You could write something like this:

public static T CastFromInt<T>(int n)
{
    return (T)(object)n;
}

but that assumes the caller uses an enum as the type of T. If they don't, it has problems. This also needlessly boxes the integer.

Upvotes: 2

Related Questions