How to supress C# warning CS0675 : Bitwise-or operator used on a sign-extended operand
I can't seem to get rid of this warning fo开发者_开发百科r the following line of code:
d.word[wrdIndex++] = d.GetWord(english) | (ulong)i;
the warning applies to the code after the assignment operator. the method GetWord returns a ulong. I've tried the following to no avail:
d.word[wrdIndex++] = (d.GetWord(english) | (ulong)i);
d.word[wrdIndex++] = d.GetWord(english) | ((ulong)i);
d.word[wrdIndex++] = ((ulong)d.GetWord(english)) | ((ulong)i);
Anyone have any ideas?
UPDATE: This question was the subject of my blog on Monday November 29th 2010.
Thanks for the great question!
You get rid of the warning by first thinking about the warning and deciding if the compiler is right to bring the problem to your attention in the first place! Are you in fact going to get incorrect results from the bitwise or should the conversion from a signed type to a larger unsigned type sign-extend the integer?
If the answer is yes then your solution is wrong. Don't eliminate the warning by tricking the compiler into still doing the wrong thing without giving you the warning. Eliminate the warning by doing the right thing: don't use a conversion that sign-extends the integer.
If the answer is no, and you want the sign extension then your solution or Hans Passant's solution is correct. However, I would put a comment to that effect in the code, because as it stands, it is hard to see that the sign extension is desirable.
int i=-1; // = 0xFFFFFFFF
ulong u1=(ulong)i; // = 0xFFFFFFFFFFFFFFFF
ulong u1a=(ulong)(long)i; // = 0xFFFFFFFFFFFFFFFF
ulong u2=(ulong)(uint)i; // = 0x00000000FFFFFFFF
So a cast from int to ulong corresponds to first sign-extending to (signed) long, and then casting away the sign.
Sorry, just got rid of it thusly:
ulong w = d.GetWord(english);
ulong u = (ulong)i;
d.word[wrdIndex++] = w | u;
精彩评论