Reputation: 21637
So I have a code that adds two integers and prints the result:
Console.WriteLine("enter number: ");
int intTemp = Convert.ToInt32(Console.ReadLine());
long sum = intTemp + 5;
Console.WriteLine($"sum is : {sum}");
But if in the console I will put the maximum value for the int type, I won't get an exception, but the result is wrong, even if I am saving the result in a long variable. Here is the output:
enter number:
2147483647
sum is : -2147483644
But if the sum variable is a long, why I am getting the wrong result?
Upvotes: 2
Views: 1293
Reputation: 86
The key is like already mentioned that you need to convert one of the values to long
to be able to retain the correct value as otherwise the result value is already corrupted before it is assigned to long
. I would like to suggest that you can use MaxValue
in these numeric types to make the calculation memory friendly if that is where you will use it for calculations. int
takes 32 bits and long
takes 64 bits. If the result of the calculation is still an int
then you can save 32 bits of storage till you really need it. In your example you could do
if (int.MaxValue - 5) < intTemp ) // it means the value will go above int range if add 5
{
// Make conversion to target type before the operation
}else{
// the value will still be in int range
}
You can use the appropriate storage type for the result then. It can become quite memory efficient if you are storing large number of results and then using them for further calculations. Hope it helps.
Upvotes: 0
Reputation: 53958
The result is not of type long
. It is of type int
and afterwards it is converted to a long in order to assign it to a variable of type long
.
That is needed to do, it is the following:
long sum = (long)intTemp + 5;
or
long sum = intTemp + (long)5;
Doing either of the above, since the one operand is of type (long), after conversion, the other would be converted also to long, in order the two values to can be added and the result would be stored to the sum
variable.
Upvotes: 3
Reputation: 106
You have to cast the int "intTemp" to a long before, because the sum only gets cast to a long after the calculation is complete
Upvotes: 1