Why does this not preclude overflow?

I tested something with LinqPad and was surprised that the following code did not raise an exception:

ulong lSmallValue = 5;
ulong lBigValue = 10;

ulong lDifference = lSmallValue - lBigValue;

Console.WriteLine(lDifference);
Console.WriteLine((long)lDifference);

This leads to the following conclusion:

18446744073709551611
-5

Fortunately, I was hoping for this behavior, but I was on the assumption that this would lead to an outlier OverflowException.

From System.OverflowException:

An overflow interrupt is triggered at runtime under the following conditions:

  • An arithmetic operation produces a result that is outside the range of the data type returned by the operation.
  • A casting or transformation operation attempts to perform a narrowing transformation, and the value of the source data type goes beyond the target data type.

Why the operation lSmallValue - lBigValuedoes not fall into the first category?

+5
source share
2

CLR . "checked".

http://msdn.microsoft.com/en-us/library/74b4xzyw%28v=vs.71%29.aspx

UPD: , "CLR via #" - . CLR #.

+11

" , , OverflowException, ."

OverflowException , .

ulong lSmallValue = 5;
ulong lBigValue = 10;
checked {
try {
    ulong lDifference = lSmallValue - lBigValue;
}
catch (OverflowException) {
    Console.WriteLine("Exception caught");
}}
0

All Articles