Typecasts:
Check out this code:
float a = 1.875;
int x = (int)a; // 1
Look at the last line: the value of a is 1.875, a fractional number, and the last line of code
is trying to put the value of a into x, which is an integer. Obviously, you can’t just transfer
the contents of a into x, so you need to lose some precision. Older languages, such as
C/C++, would do this for you automatically, and chop 1.875 down to 1 in order to fit it
into the integer (the process is called truncation). If you tried typing this line into a C#
program, however, you would get a compiler error:
x = a; // error! Cannot implicitly convert type ‘float’ to ‘int’
Of course, this code works perfectly well in older languages, so a lot of people will automatically
dismiss C# as “difficult to use.” I can hear them now: “Can’t you just automatically
convert the float to the integer, you stupid compiler?”
Well, the compiler isn’t actually stupid; it’s trying to save you some time debugging. You
may not realize it, but a common source of bugs in programs is accidental truncation.
You might forget that one type is an integer and some important data may get lost in the
translation somewhere. So C# requires you to explicitly tell it when you want to truncate
data. Tables 2.5 and 2.6 list which conversions require explicit and implicit conversions.
Explicit/Implicit Conversions, Part 1
From byte sbyte short ushort int uint
byte I E I I I I
sbyte E I I E I E
short E E I E I E
ushort E E E I I I
int E E E E I E
uint E E E E E I
long E E E E E E
ulong E E E E E E
float E E E E E E
double E E E E E E
decimal E E E E E E
Explicit/Implicit Conversions, Part 2