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: Read More »
