While using these methods I found a shortcoming... there is no support for flags! So this is how I improved it:
public static bool TryParseEnum(object value, out EnumType result)
{
result = default(EnumType);
if (value == null) return false;
var type = typeof (EnumType);
if (!type.IsEnum) return false;
int iValue;
return Int32.TryParse(value.ToString(), out iValue)
? TryParseEnum(iValue, out result)
: TryParseEnum(value.ToString(), out result);
}
public static bool TryParseEnum(int value, out EnumType result)
{
result = default(EnumType);
var type = typeof(EnumType);
if (!type.IsEnum) return false;
result = (EnumType)Enum.Parse(type, value.ToString());
// Verify if the result is valid,
// Enum.Parse might just return the input value, while this is not a defined value of the enum
if (result.ToString().Contains(", ") || Enum.IsDefined(type, result))
return true;
result = default(EnumType);
return false;
}
public static bool TryParseEnum(string value, out EnumType result)
{
result = default(EnumType);
if (string.IsNullOrEmpty(value)) return false;
var type = typeof(EnumType);
if (!type.IsEnum) return false;
value = value.ToUpperInvariant();
try
{
result = (EnumType)Enum.Parse(type, value, true);
return true;
}
catch (ArgumentException)
{
return false;
}
}
:edited: Edited the object method to use the two other methods, this should be more reliable for both normal enums and bit flag enums. Casting/parsing values which are non-numeric and non-string values is anyway not possible in .NET.
modified on Wednesday, February 10, 2010 6:31 AM