Why operators << and >> are not realized for flag enums in C#?

191 Views Asked by At

I want to do something like this, but I can't:

[Flags]
enum SomeEnum : int
{ 
 None = 0,
 A,
 B,
 C
}

SomeEnum en = SomeEnum.A;
en <<= 1; //Expect en == SomeEnum.B but I recieve an error here

For what It has been done so?

3

There are 3 best solutions below

0
On

Enums are not bit fields in themselves. The whole point of enums is to abstract away any underlying values. Using shift operators implies knowing what these values are.

However, if you really want to shift, just cast:

en = (SomeEnum)((int)en << 1);
6
On

A [Flag] enum can hold a combination of flags. Shifting a combination will rarely result in sensible meaning

SomeEnum en = SomeEnum.A | SomeEnum.B;
en <<= 1; //Expect what?

You can cast to int, and do what you like if you know what you're doing

NOTE: if you really want to use SomeEnum without explicitely casting, you could wrap it with a type like Pseudo<SomeEnum> which I defined here: Is it possible to wrap integer and call it like integer?

Note that it is really a proof of concept thing, but you can see how it would work from there

0
On

I would say that this is because you "Cannot apply operator '<<=' to operands of type 'SomeEnum' and 'int'". So instead you have to do the rather less elegant,

var en = SomeEnum.A;

en = (SomeEnum)((int)en << 1);

Which explicitly does the type conversion or, if you prefer you can wait for <<= to be implmented or for the Enum implicit cast to int operator to implemented, Neither of which seems likely, its not somthing that should be done by accident.

You could write you own extension method to achieve the same but I think that would need to use some reflection to handle the different base types of Enum