Tuesday, September 1, 2009

Extension Function For Enumeration Type in C#

I have the following enum
enum OrderStatus : int
        Draft = 1,
        Pending = 2,
        Approved = 3,
        Rejected = 4

Now if i want to get the enum value to a variable then i have to write the following line of code

int currentOrderStatus=(int)OrderStatus.Draft;

I can do the same thing in an alternative manner i.e by adding an extension function instead of explicit conversion. Here is the code for that

public static class EnumExtension
        public static int ToInteger(this Enum value)
            object objValue = Enum.Parse(value.GetType(), value.ToString());
            return (int)objValue;

Now I can write

int currentOrderStatus=OrderStatus.Draft.ToInteger();

Happy coding.... Thanks

No comments:

Post a Comment