Created
September 26, 2013 19:35
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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