Skip to content

Instantly share code, notes, and snippets.

@davetrux
Created September 26, 2013 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davetrux/6719396 to your computer and use it in GitHub Desktop.
Save davetrux/6719396 to your computer and use it in GitHub Desktop.
A function for .Net to perform something like Enum.TryParse. See http://blog.davidtruxall.com/2005/12/08/generics-and-enums-or-enum-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>
public static 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;
}
//input not found in the Enum, fill the out parameter
// with the first item from the enum
var values = Enum.GetNames(typeof(T));
returnValue = (T)Enum.Parse(typeof(T), values[0], true);
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment