The normal is if you exceed the limit of the maximum possible number in the type it turns and start again in the smallest possible number of the type, then the integer would be negative.
Unless you ask for the operation to be checked. Then an exception would be generated. I answered about this in What is checked in the code in C#?.
All numeric types of . NET have a constant indicating the largest and smallest possible number. So to check if a whole will burst need to buy with them. Something like this:
if (x <= Int32.MaxValue - y) {
z = x + y;
}
Just remembering that if this value is in some shared object and can be accessed concurrently in threads there may be a running condition. For that there is the checked
. In such a situation it is better to do the operation and check if the account went wrong by catching the exception.
In the case of the type double
is more complicated and has the method Double.IsPositiveInfinity()
to check if the value "exceeded". There are other techniques, but I believe this is the most reliable. Given the non-exhaustive nature of the type there are no guarantees.
var x = Double.MaxValue;
double y = 0;
if (!Double.IsPositiveInfinity(x * 2)) {
y = x * 2;
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
Please avoid long discussions in the comments; your talk was moved to the chat
– Maniero