6

I'm a little confused about the behavior of the ulong type. I understand it to be a 64-bit integer used for positive numbers (max value 18,446,744,073,709,551,615). I just started using it because I need really big positive numbers, but there's some strange behavior I don't understand around potential negative numbers.

ulong big = 1000000;    //Perfectly legal

ulong negative = -1;    //"Constant value "-1" cannot be converted to a ulong" Makes sense


//Attempt to sneak around the -1 as a constant compile-time error
int negativeInt = -1;
ulong negativeUlongFail = negativeInt;    //"Cannot implicitly convert 'int' to 'ulong'.
                                 //An explicit conversion exists (are you missing a cast?)"
//So I add casting
ulong negativeUlong = (ulong)negativeInt;    //But this yields 18446744073709551615

//Try and get a negative number indirectly
ulong number = 0;
number = number - 10;  //now number is 18446744073709551615 but no underflow error

What's going on? How come some underflow errors are caught and others aren't and don't even throw exceptions? Can I detect these?

I focused on getting negative numbers by underflowing, but I've seen similar things when getting numbers bigger than the max value and overflowing.

I'm not sure if they're technically Errors or Exceptions, so please forgive me if I used incorrect terminology

1
  • 1
    The compiler has under/overflow checking enabled by default, the runtime does not. The latter is a project setting, Project > Properties > Build tab > Advanced button. Turning on the checkbox is a good idea for the Debug configuration. Not so much for the Release build, the check is pretty expensive. Override these defaults on-the-fly with the checked and unchecked keywords. Jul 24, 2017 at 9:03

1 Answer 1

5

if you want the underflow (or overflow) exception to be thrown, try this instead :-

checked
{
    ulong number = 0;
    number = number - 10;
}

by default the exception gets swallowed (it runs in unchecked).

see official documentation

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/checked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.