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

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: