Monday, August 18, 2008

How to convert from string to enum using C# and generics

In order to convert from a string to an enumeration in .NET you can use the method Enum.Parse as follows:


public enum SortExpressions
{
 FirstNameAsc,
 FirstNameDesc,
 LastNameAsc,
 LastNameDesc
}

var value = "lastnameasc";
var sortExpression = (SortExpressions) Enum.Parse(typeof(SortExpressions), value, true);

Since this operation is often needed we should make a ConvertToEnum method so we can reuse it. But instead of returning it as the typical object type, we should rather use generics to return it as the actual type:


/// 
/// Converts a string to the specificed enumeration.
/// 
public T ConvertToEnum(string value, T defaultEnum)
{
 try
 {
  return (T) Enum.Parse(typeof(T), value, true);
 }
 catch
 {
  return defaultEnum;
 }
}

A try/catch is used instead of the method Enum.IsDefined as it's case-sensitive.

And this is how you can use our new ConvertToEnum method:


var value = "lastnameasc";
var sortExpression = ConvertToEnum(value, SortExpressions.FirstNameAsc);