Does anyone know (and perhaps: since when) the -= operator is supported on enum values?

I was happily coding away today when I, for some reason, wrote this to exclude a value from a flags enum:

flags -= FlagsEnum.Value1;

After rereading and evaluating my code, I was surprised that it compiled actually worked.

Writing the statement as

flags = flags - FlagsEnum.Value1

however does not compile.

I couldn't find anything in the documentation and on internet sofar. Also, other operators (apart from the bit operators, of course) are not supported: += (including a flag) , *= (intersection in Pascal) don't work.

Is this some syntactic sugar built into the C# compiler? If so, any reason why they chose not to include other operators?

Are you sure it actually works? You could be deceived by the fact that a subtraction will appear to exclude the bit. Have you tried it on a flags variable where the bit corresponding to Value1 is already 0?
–
TormodMar 12 '11 at 18:36

Using it like that is pretty unsafe. It will only work as enum when FlagsEnum.Value1 is already in the flags.
–
Jaroslav JandekMar 12 '11 at 18:49

@Jaroslav: I never do it like that, but it just happened to roll out of my fingers. I blame it on Delphi (with its nice set operators), but I was quite (although now less) surprised that it compiled. And, as Marc pointed out, the result might not be wat you expect.
–
Willem van RumptMar 12 '11 at 18:58

2 Answers
2

Enumeration subtraction. Every enumeration type implicitly provides the following predefined operator, where E is the enum type, and U is the underlying type of E:
U operator –(E x, E y);
This operator is evaluated exactly as (U)((U)x – (U)y). In other words, the operator computes the difference between the ordinal values of x and y, and the type of the result is the underlying type of the enumeration.

Aaah...the specs. :) The only place I didn't look (and almost never look, to be honest). Thanks. Any idea why the += operator was not defined in a similar way for enums?
–
Willem van RumptMar 12 '11 at 18:43

@Marc: I know how enums work. That's why I asked the question in the first place.
–
Willem van RumptMar 12 '11 at 18:46

3

@Willem - ou missed my point; you claim "it works"; the spec says this is integer subtaction. Which isn't what you want to remove a bit (question). so IMO this doesn't work in the way you think (question).
–
Marc Gravell♦Mar 12 '11 at 18:48

@Marc: Hmmm...you're right. One up :). For what it's worth: I was definitely not planning on using it. Don't know what triggered me to write the statement like that, but most likely it was a Delphi-ism from yesterday. I was mightely surprised though.
–
Willem van RumptMar 12 '11 at 18:52