SleekPanther
SleekPanther

Reputation: 374

C# ulong overflow / underflow somehow allowed

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

Upvotes: 6

Views: 2007

Answers (1)

Keith Nicholas
Keith Nicholas

Reputation: 44298

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

Upvotes: 5

Related Questions