Generics and Enums or Enum.TryParse
I have a case where the user is entering strings into the application, and I have to match that string with the values from a given Enum. Normally that is not too difficult of a task, just convert the enum item to a string and compare, but in this instance I have a bunch of enums to do this with, so I didn’t want to write a separate function for each enum type. So I figured generics might provide a solution and here is what I came up with, which is loosely based on the idea of int.TryParse:
/// <SUMMARY>
/// Takes a string that represents an enum member
/// and returns the enum member
/// </SUMMARY>
/// <TYPEPARAM name="T">An Enum</TYPEPARAM>
/// <PARAM name="input">
/// The string that is the enum member name, case does
/// not matter
/// </PARAM>
/// <PARAM name="returnValue">
/// The value from the enum that matches the string, or the
/// first value of the enum /// </PARAM>
/// <RETURNS>
/// True when there is a match, false when not
/// </RETURNS>
/// <REMARKS>
/// - When no match the first item in the enum is returned
/// - The where clause attempts to constrain the input of T /// at compile time to be an Enum
/// </REMARKS>
private bool GetEnumValue<T>(string input, out T returnValue) where T : struct, IComparable, IFormattable, IConvertible
{
if(Enum.IsDefined(typeof(T), input))
{
returnValue = (T)Enum.Parse(typeof(T), input, true);
return true;
}
else //input not found in the Enum, fill the out parameter // with the first item from the enum
{
string[] values = Enum.GetNames(typeof(T));
returnValue = (T)Enum.Parse(typeof(T), values[0], true);
return false;
}
}


