You are doing a lot of work that can be done for you. For example, if your enum
is declared with the FlagsAttribute
then Enum.Parse
will parse comma separated values for you.
public static T ParseFlags<T>(string value) where T : struct
{
T result;
ulong temp;
if (Enum.TryParse(value, out result))
{
return result;
}
string hexNum = value.StartsWith("0x") ? value.Substring(2) : value;
if (ulong.TryParse(hexNum, NumberStyles.HexNumber, null, out temp))
{
return (T)Enum.ToObject(typeof(T), temp);
}
throw new ArgumentException("value could not be parsed");
}
I tested this with various Flags enum types with short
, int
, and ulong
backing values.