I have an object. Usually it is either long
or string
, so to simplify the code let's assume just that.
I have to create a method that tries to convert this object to a provided enum. So:
public object ToEnum(Type enumType, object value)
{
if(enumType.IsEnum)
{
if(Enum.IsDefined(enumType, value))
{
var val = Enum.Parse(enumType, (string)value);
return val;
}
}
return null;
}
With strings it works well. With numbers it causes problems, because a default underlying type for enum is int
, not long
and IsDefined
throws an ArgumentException
.
Of course I can do many checks, conversions or try-catches.
What I want is to have a clean and small code for that. Any ideas how to make it readable and simple?