My contribution to the Enum.TryParse methods for .NET 3.5

Update - Added a try catch for those times when someone passes in an invalid value.

public static class EnumExtentions
{
#region Static Methods  /// <summary>
/// The same signature as .NET 4.0
/// </summary>
/// <typeparam name="TEnum"></typeparam>
/// <param name="value"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool TryParse<TEnum>(this string value, out TEnum result)
where TEnum : struct
{
// for .NET 4.0 replace with:
// return Enum.TryParse<TEnum>(value, false, out result);
return EnumExtentions.TryParse<TEnum>(value, false, out result);
}

/// <summary>
/// The same signature as .NET 4.0
/// </summary>
/// <typeparam name="TEnum"></typeparam>
/// <param name="value"></param>
/// <param name="ignoreCase"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool TryParse<TEnum>(this string value, bool ignoreCase, out TEnum result)
where TEnum : struct
{
// for .NET 4.0 replace with:
// return Enum.TryParse<TEnum>(value, false, out result);

result = default(TEnum);
try
{
Type typeOfTEnum = typeof(TEnum);
StringComparison stringComparison = ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture;

foreach (string item in Enum.GetNames(typeOfTEnum))
{
if (item.Equals(value, stringComparison))
{
result = (TEnum)Enum.Parse(typeOfTEnum, value, ignoreCase);
return true;
}
}
if (Enum.IsDefined(typeOfTEnum, Convert.ChangeType(value, (Enum.GetUnderlyingType(typeOfTEnum)))))
{
result = (TEnum)Enum.Parse(typeOfTEnum, value);
return true;
}
}
catch
{
return false;
}
return false;
}

#endregion Static Methods 
}

Comments

Popular Posts