Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent bitwise OR combinations of enum values?

Tags:

c#

enums

flags

I know that you can use FlagsAttribute to instruct the compiler to use bitfields for an enumeration.

Is there a way to specify that enum values cannot be combined with bitwise OR?

Example:

enum OnlyOneOption
{
   Option1,
   Option2,
   ...
}

In this example there is nothing stopping a developer from writing OnlyOneOption.Option1 | OnlyOneOption.Option2. I would like to forbid it, at compile time if possible.

like image 938
Mickael Thumerel Avatar asked Jul 22 '16 09:07

Mickael Thumerel


3 Answers

Compile-time check

Recently, Eric Lippert (one of the guys that worked on the C#-compiler while he was at Microsoft) blogged about his top 10 regrets about C#, number four being that

In C#, an enum is just a thin type-system wrapper over an underlying integral type. All operations on enums are specified as actually being operations on integers, and the names of enum values are like named constants.

So in principle, you cannot get the compiler to choke on

OnlyOneOption option = OnlyOneOption.Option1 | OnlyOneOption.Option2;

because in terms of integers, that operation looks perfectly fine. What you can do, as you indicate, is not provide the FlagsAttribute - which is already a good hint to developers.

Since you cannot overload operators on enums either, you have to resort to runtime checking.

Run-time check

What you can do, is any time you need the enum, check for exact equality and throw an exception when a combination of values is used. Quickest and cleanest way is to use a switch:

// Use the bit pattern to guarantee that e.g. OptionX | OptionY
// never accidentally ends up as another valid option.
enum OnlyOneOption { Option1 = 0x001, Option2 = 0x002, Option3 = 0x004, ... };

switch(option) {
  case OnlyOneOption.Option1: 
    // Only Option1 selected - handle it.
    break;

  case OnlyOneOption.Option2: 
    // Only Option2 selected - handle it.
    break;

  default:
    throw new InvalidOperationException("You cannot combine OnlyOneOption values.");
}

Non-enum solution

If you do not insist on using an enum, you could resort to the classical (Java-ish) static pattern:

class OnlyOneOption
{
    // Constructor is private so users cannot create their own instances.
    private OnlyOneOption() {} 

    public static OnlyOneOption OptionA = new OnlyOneOption();
    public static OnlyOneOption OptionB = new OnlyOneOption();
    public static OnlyOneOption OptionC = new OnlyOneOption();
}

and here OnlyOneOption option = OnlyOneOption.OptionA | OnlyOneOption.OptionB; will fail with error CS0019: "Operator '|' cannot be applied to operands of type 'OnlyOneOption' and 'OnlyOneOption'".

The downside is that you lose the ability to write switch statements because they actually require a compile-time constant conversion to int (I tried providing a static public implicit operator int that returns a readonly field but even that is not enough - "A constant value is expected").

like image 132
CompuChip Avatar answered Nov 14 '22 07:11

CompuChip


No, you can't prevent that. Not specifying the [Flags] attribute will not disallow a user from the following:

enum Option
{
    One = 1,
    Two,
    Three
}

var myOption = Option.One | Option.Two;

Furthermore, something perfectly legal is the following:

var myOption = 0; //language quirk IMO, 0 being implicitly convertible to any enumeration type.

or

var myOption = (Option)33;

Is this a problem? Well no, not really; if your logic only considers options One, Two or Three then simply enforce it:

public Foo Bar(Option myOption)
{
     switch (myOption)
     {
         case Option.One: ...
         case Option.Two: ...
         case Option.Three: ...
         default: //Not a valid option, act in consequence
     }
}

Do note that if you have (suspect) code that decides based upon the underlying value of the enumeration:

if (myOption < Option.Three) { //expecting myOption to be either One or Two...

Then you are most definitely not using the right tool for the job; myOption = 0; or myOption = (Option)-999 would be a problem.

like image 31
InBetween Avatar answered Nov 14 '22 08:11

InBetween


Add validation

enum MyEnum
{
  Value1 = 1,
  Value2 = 2
}

  MyEnum e = MyEnum.Value1 | MyEnum.Value2;
  var isValid = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Count(x => e.HasFlag(x)) == 1;
like image 2
Nina Avatar answered Nov 14 '22 07:11

Nina