2

Is there a way to use unchecked for a whole program or a whole block ?

I'm translating something from java that has the type long and lots of comparisons with constants that are unsigned long... Some places there a some switch's with 20~30 cases... Do I have to uncheck every case individualy or is there a faster/easier way to do it?

case 101: 
   return jjMoveStringLiteralDfa5_0(active0, 0x8002010000000000L, active1, 0x1L);

I have to change to:

   return jjMoveStringLiteralDfa5_0(active0, unchecked((long)0x8002010000000000L), active1, 0x1L);

but there are many cases... and it is in a parser generator with lots of IF's, so It would be better to have something to suppress those checks in the whole file instead of searching every possible place that would generate those unsigned long constants...

There is a way to set that on Visual Studio options but since I'm generating a parser I wanted to know if I could make that parser automaticaly not check for overflows/underflows, is that possible?

nightshade
  • 638
  • 5
  • 15

1 Answers1

3

If you want to use hexadecimal literals to express negative integers via the two's complement convention, you simply have to provide both a cast and an explicit use of the unchecked keyword. Example:

sbyte b = unchecked((sbyte)0xAB);
short s = unchecked((short)0xABCD);
int i = unchecked((int)0xABCDABCD);
long l = unchecked((long)0xABCDABCDABCDABCD);

It is not enough that the default context (as defined by C# compiler switch and/or csproj file) is the "unchecked" context.

If you can use the unsigned types (for example uint), you won't have this problem. But the unsigned types are typically not used by the BCL, and are not considered "CLS compliant".


Just make it entirely clear, with positive literals you need neither cast nor unchecked keyword:

sbyte b = 0x2E;
short s = 0x2E3F;
int i = 0x2E3F2E3F;
long l = 0x2E3F2E3F2E3F2E3F;

For constant expressions implicit conversions exist to make this easy, see Implicit constant expression conversions.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
  • but is there a way for me to make that cast implicit so I won't have to be casting all the time? like: "whenever you need to convert ulong to long, do like this (my_conversion)" – nightshade Jun 16 '14 at 22:21
  • @nightshade You would have to call your own method, which could be an extension method. EDIT: The conversion would no longer be done at compile-time; it would be a run-time thing (but possibly "empty" performance hit). – Jeppe Stig Nielsen Jun 16 '14 at 22:26
  • Hum... guess I'll just hit CTRL + F and find all the "0x" string in the part generating the code and add (long) or (int) before it then... – nightshade Jun 16 '14 at 22:38