AlanS

AlanS
- Name: [not set]
- Favorite Languages: [not set]
- Website: [not set]
- Location: [not set]
- About Me: [not set]
-
C# Snippet Tutorial - How to get an Enum from a String
10/27/2010 - 06:01
or throw in a bit of error checking ...
/// <summary>
/// Converts a sting into an element of the specified enum
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="enumString"></param>
/// <returns></returns>
public static T ConvertStringToEnum<T>(string enumString)
{
try
{
return (T)Enum.Parse(typeof(T), enumString, true);
}
catch (Exception ex)
{
// Create an instance of T ... we're doing this to that we can peform a GetType() on it to retrieve the name
//
T temp = default(T) ;
String s = String.Format("'{0}' is not a valid enumeration of '{1}'", enumString, temp.GetType().Name);
throw new Exception(s, ex);
}
}
Recent Comments