Code Snippet - How to Use Extension with Enum
2014/5/31 min read
bookmark this
In C# you sometime have to convert enum to Int value. Like following example
public enum NameType
{
Undefined,
TypeA,
TypeB,
TypeC,
TypeD,
TypeE = 99
}
You could write like this.
(int)NameType.TypeE
But what if just write like this.
NameType.TypeE.ToInt();
Here is what I'm doing to write a Enum Extension Class. This is just a basic example.
public static class EnumHelper
{
public static int ToInt(this Enum enumValue)
{
object val = Convert.ChangeType(enumValue, enumValue.GetTypeCode());
return Convert.ToInt32(val);
}
}