Extension Methods and Generics: Match a String To a Enum

To match a string value to a enum you have a couple options.

  1. You could loop through the enum values until you find a match.
  2. Or a better option, use the Enum.Parse method to convert the string to the equivalent enumerated object.

However, when exchanging data with third parties you might find the need to convert between strings and enums often.

With a little help from generics I wrote a quick extension method to make this even easier.


public static T FromStringToEnum<T>(this String stringValue, T enumToGet)
    if (!typeof(T).IsEnum) return default(T);
    return (T)Enum.Parse(typeof(T), stringValue); 

public enum Number { one, two }

 public void FromStringtoEnum_EnumReturned()
    string f = "one";
    var e = f.FromStringToEnum( new Number());
    Assert.AreEqual(Number.one, e);

 public void FromStringtoEnum_NonEnumPassed_DefaultReturned()
    string f = "one";
    var e = f.FromStringToEnum("");
    Assert.AreEqual( null, e);

The first line validates that T  is an Enum, if not it will return the default value of the type.   The second line is the implementation of the parse method using generics to get the type of the enum.


About Shawn Sweeney

I'm a father, software developer, and runner. I blog about things related. View all posts by Shawn Sweeney

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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: