Click here to Skip to main content
16,015,040 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i had been asked this question in a technical test and i want to know it's answer
'if you have 2 variables one is int and the other is double you want to make casting for one of the variables to the other one which one will you choose to cast to and why ?'
Posted

You usually don't choose 'based on the variable type'. You usually cast (if you cannot avoid it) based on the problem 'requirements'.
:)
 
Share this answer
 
int is of 4 bytes, and, double is of 8 bytes in c#

Casting means cropping some bits of a variable to fit a it's value into a smaller sized variable's bucket of bits and hence stripping off some value to fit the type of the target variable (Applicable for primitive type variables)

So, in this case, if we have the following two variables:

int a;
double d = 2.567;


we would need to cast the double variable d to an int if we want to assign it to the int variable a.
a = (int)d; // a would have value assigned to 2 in this case.

So, casting is a "narrowing conversion" here as the binary value representations of 8 bytes cannot fit into a 4 byte variable.

However, if we need to assign an int value to a double variable as follows, we wouldn't require any casting:
int a = 5;
double d;

d = a; // d would have value assigned to 5.0

This is a "widening conversation" as the binary value representations of 4 bytes are being assigned to a 8 byte variable.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900