I wrote a code for checking typecasting in C#. The following code:
using System;
class Convert{
public static void Main(){
double a=14.25,b=26.12;
var z=(int)(a*b);
Console.WriteLine("z= "+z);
Console.ReadKey(true);
}
}
Gave output:
z=372
But when i modified the code a bit then i got a big difference between the value of z earlier and after modification.
using System;
class Convert{
public static void Main(){
double a=14.25,b=26.12;
var z=(int)a*b; // Modified part
Console.WriteLine("z= "+z);
Console.ReadKey(true);
}
}
Gave output:
z=365.68
I don’t understand that why is there so much difference after removing the brackets from the original code?
Without the outer parentheses, the
(int)cast applies toaonly.Therefore, you end up multiplying a truncated integer by a normal double, and type inference turns
varintodouble.With the parentheses, the cast applies to the result of the multiplication. Therefore, the entire result gets truncated, and type inference turns
varintoint.Thus, changing
vartodoublewould have no effect on either example. (in the second case, it would assign the truncatedintto adoublevariable)Changing
vartointwould turn the second example into a compiler error.