Compiler error or misunderstanding? Or a short operator

I have a line of code that gives me a warning (CS0675) in VS2015, but not in 2013.

shortValue |= (short)anEnum; 

Warning CS0675 The bitwise or operator used in the extended character operand; consider casting with a smaller unsigned type first. The compiler implicitly expanded and expanded the sign of the variable, and then used the resulting value in a bitwise OR operation. This can lead to unexpected behavior.

Obviously, the renaming occurs, and short expands to an int, the applied or operator, and then the result assigns the result to the short one.

If I changed the code to shortValue = shortValue | (short)anEnum; shortValue = shortValue | (short)anEnum; , I will get compiler error CS0266. But a bitwise OR should be true for shorts (in both cases, I think). If I hover over | , it will be shown as an int statement, am I missing something or should I report this as an error?

PS: I know that I can eliminate the warning / error by using = instead of |= and casting the result to short.

+5
source share
1 answer

If you look at the C # specifications (in particular, in “Logical Integer Operators”), you will see that for the logical OR operator, there is only a definition for int , uint , long , ulong :

 int operator |(int x, int y); uint operator |(uint x, uint y); long operator |(long x, long y); ulong operator |(ulong x, ulong y); 

Also in bit-twisting: what does warning CS0675 mean? Eric Lippert claims that:

" int , uint , long and ulong "

there are bitwise or operators

The operator is valid for short , but only in the sense that the short value can be increased to int . However, the return value of this operator is (at least) a int .

So, technically speaking, according to the specifications, this does not seem to be an error, since using |= extends the signed value to int, which gives a warning, and regular | results in int that must be discarded to assign short .

However , since the compiler can really know that both operands are initially short s, both expand to int , and the result will eventually be saved back to short it does not really matter that the operands are expanded. The extension will be lost when pressed from int to short .

Thus, either the VS2013 compiler was smarter with its warnings than VS2015, or VS2015 corrects the error and warns where VS2013 failed. Only the people behind the compiler can answer this, but I assume this is really a mistake (EDIT: and this ).

+5
source

Source: https://habr.com/ru/post/1233200/