Actually 99999*99999 = 9,999,800,001
which is much greater than 2,147,483,647
which is int32.Max
which results in an overflow. In C# the default context for arithmetic operations is unchecked
context, which means in case of an overflow, no exception will be throws, and instead, the result will be truncated by discarding the high-order bits which doesn't fit.
To change the default behavior, you need to run your arithmetic operation in a checked
context.
If you want to see the exception, you need can use checked
like this:
int number = 99999;
int sqr = checked(number * number);
Then you receive:
System.OverflowException: 'Arithmetic operation resulted in an overflow.'
If you want still use an integral type but still handle such large numbers, you may want to use long
data type:
long number = 99999;
long sqr = checked(number * number);
Which correctly calculate the result which is 9,999,800,001
and store it in the sqr
variable.
Learn more: