Append Enum Flags to a Parameter in a Loop (Bitwise Appending)

bigmac picture bigmac · Nov 29, 2011 · Viewed 11.6k times · Source

In C#, I am trying to "add" values to a parameter that accepts enumerated flags. I can do it on one line with a bitwise operator "|", but I can't seem append to the parameter in a loop.

I have the following Enum specified as Flags.

[Flags]
public enum ProtectionOptions
{
  NoPrevention = 0,
  PreventEverything = 1,
  PreventCopying = 2,
  PreventPrinting = 4,
  PrintOnlyLowResolution = 8
}

Now, I can easily use the following code to add flag values to the parameter:

myObj.Protection = ProtectionOptions.PreventEverything | ProtectionOptions.PrintOnlyLowResolution;

But, what I want to do, is to get a list of protection options from a CSV string (from the Web.Config), loop through them and add them to my myObj.ProtectionOptions property. I don't know how to do this in a loop without using the bitwise OR "|" operator. Here is what I am wanting to do:

string protectionOptionsString = "NoPrevention, PreventPrinting";
string[] protectionOptions = protectionOptionsString.Split(',');
foreach (string protectionOption in protectionOptions)
{
  myObj.Protection += (ProtectionOptions) Enum.Parse(typeof (ProtectionOptions), protectionOption.Trim());
}

Conceptually, this is what I want, but I can't "+=" the values in the loop to the parameter.

Answer

Motti Shaked picture Motti Shaked · Nov 29, 2011

You don't need to split. Enum.Parse is capable of parsing multiple values if you use the [Flags] attribute on the enum definition, which you did. Just parse and use the |= operator to "add" the flags.

string protectionOptionsString = "NoPrevention, PreventPrinting";
myObj.Protection |= (ProtectionOptions)Enum.Parse(typeof(ProtectionOptions), protectionOptionsString);