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;
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;
This is a "
widening conversation
" as the binary value representations of
4 bytes
are being assigned to a
8 byte
variable.