String To Enum Generic Function

I used to develop mainly in VB and found that converting a string to an enum was a pain!

Today i had to create several methods that did that for different types and after about 2-3 conversion methods I realized that I was doing it the hard way.

So I made a simple string to enum conversion function like this:

public static T ConvertStringToEnum<T>(string type) {
     return (T)Enum.Parse(typeof(T), type);
}

I only wish you could make static extension methods. Then I could do something like this (with any extra syntax that they needed to add to make it static):

Note the below won’t work.

public static class EnumExtensions {
     public static T Parse<T>(this Enum e, string value) {
         return (T)Enum.Parse(typeof(T), value);        
     }  
}
Advertisements