I have an method for enums that looks like this:
public static TEnum GetEnumByStringValue<TEnum>(string value) where TEnum : struct, IConvertible, IComparable, IFormattable
{
if(!typeof(TEnum).IsEnum)
{
throw new ArgumentException("TEnum must be an enumerated type.");
}
Type type = typeof(TEnum);
FieldInfo[] fieldInfos = type.GetFields();
foreach (FieldInfo fieldInfo in fieldInfos)
{
StringValue[] stringValues = fieldInfo.GetCustomAttributes(typeof(StringValue), false) as StringValue[];
if (stringValues != null)
{
foreach (StringValue stringValue in stringValues)
{
if (stringValue.Value.Equals(value))
{
return (TEnum)Enum.Parse(typeof(TEnum), fieldInfo.Name);
}
}
}
}
throw new ArgumentOutOfRangeException("value", "Value was not found in enum's string values.");
}
I'd like to implement a TryGetEnumByStringValue
, that returns true or false instead of throwing an exception similar to the concept of int.Parse
and int.TryParse
. The way I see it, in my new method I could just call my other one, catch the exceptions (if any) and return accordingly, or I could refactor the existing one to return bool
and again in my new method simply call the existing one and throw an exception if it returns false.
If I go with option 2 I lose exact exception details, and if I go with option 1 the exceptions are still thrown (I've always been taught exceptions are slow).
I could also refactor the existing one to take a bool
indicating whether to throw exceptions or not, but that doesn't quite sit right with me.
Is there a pearl of wisdom I've missed for this sort of method style or pattern?