0

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.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Josh Taylor
  • 532
  • 2
  • 8
  • 1
    http://msdn.microsoft.com/en-us/library/system.enum.tryparse.aspx – m0s Aug 30 '13 at 20:53
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Aug 30 '13 at 20:59

1 Answers1

7

Enum.Parse can already combine multiple flags. Quoting from the documentation:

Remarks

The value parameter contains the string representation of an enumeration member's underlying value or named constant, or a list of named constants delimited by commas (,). One or more blank spaces can precede or follow each value, name, or comma in value. If value is a list, the return value is the value of the specified names combined with a bitwise OR operation.

So you could do it like this:

public static T ParseFlagsEnum<T>(string[] values)
{
  return (T)Enum.Parse(typeof(T), string.Join(",", values));
}
Community
  • 1
  • 1