I'm trying to evaluate an enum with the FlagsAttribute applied as shown below. The problem is the ridiculous amount of code its taking to ensure the proper if statement runs. I've got four if statements that should only execute if specific combinations of the enum are set but nothing else:
Detecting the existence of the required flags is easy but I also have to ensure that no other flags are set which is a ridiculous amount of code to type and looks like a maintenance nightmare.
[Flags]
public enum AccessModifierType : short
{
Infer = 1,
Public = 2,
Privileged = 4,
Private = 8,
Static = 16
}
Can anyone re-write this if statement to be more concise?
if ((Model.CurrentContext.CurrentAccessModifierType & AccessModifierType.Public) == AccessModifierType.Public
&& (Model.CurrentContext.CurrentAccessModifierType & AccessModifierType.Static) != AccessModifierType.Static
&& (Model.CurrentContext.CurrentAccessModifierType & AccessModifierType.Privileged) != AccessModifierType.Privileged
&& (Model.CurrentContext.CurrentAccessModifierType & AccessModifierType.Private) != AccessModifierType.Private){
}
It's not clear how your final sample relates to your original requirements (I get the feeling that Infer has some special meaning?) but if you're looking for a specific bit combination and nothing else, why not just use an equality test against the exact expected enum value (assembled through bitwise ORs)?
if(myUnknownFlagsEnumValue == (MyEnum.RequiredFlag1 | MyEnum.RequiredFlag2))
{
...
}
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