Tag Archives: Enum

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.

Example:

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 }

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

[TestMethod]
 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.


		
Advertisements

%d bloggers like this: