Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 434
bigmac Avatar asked Nov 29 '22 17:11

bigmac


1 Answers

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);
like image 156
Motti Shaked Avatar answered Dec 01 '22 08:12

Motti Shaked