C# add extension to all enum

Posted in C#, on 5/4/2014

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);
        }
    }