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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With