I have an array of string values that I would like to have set flags on a Flags Enum object. I have several of these and was looking for a more generic way to pass in the type of the Flags enum and not have to duplicate the method for each Flags Enum type. This is what I have currently:
public static MyFlagsEnum ParseFlagsEnum(string[] values)
{
MyFlagsEnum flags = new MyFlagsEnum();
foreach (var flag in values)
{
flags |= (MyFlagsEnum)Enum.Parse(typeof(MyFlagsEnum), flag);
}
return flags;
}
I was looking for a more generic way of doing the same thing, while being able to use any Flags Enum type.
Enum.Parse
can already combine multiple flags. Quoting from the documentation:So you could do it like this: