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 to a only.
Therefore, you end up multiplying a truncated integer by a normal double, and type inference turns var into double.
With the parentheses, the cast applies to the result of the multiplication. Therefore, the entire result gets truncated, and type inference turns var into int.
Thus, changing var to double would have no effect on either example. (in the second case, it would assign the truncated int to a double variable)
Changing var to int would turn the second example into a compiler error.
brackets set prioryty
var z=(int)(a*b);//(a*b) cast to int
var z=(int)a*b;//a cast to int and myltiply with b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With