Your question is not related to unboxing operation only. Actually it should sound as "Why should I use explicit conversion?" Consider following example:
int i = 123;
long l = i;
int j = (int)l; // OMG why??
The answer is simple and you can find it in C# specification 6.2 Explicit conversions:
The explicit conversions are conversions that cannot be proven to
always succeed, conversions that are known to possibly lose
information, and conversions across domains of types sufficiently
different to merit explicit notation.
In example above you might lose information, because long
can hold values which do not fit int
range. But you will never lose information when assigning int
to long
:
long l = i; // safe
In your example you need explicit conversion because implicit conversion cannot be proven to always succeed. Variables of object
type can reference
literally any type. What about string?
object o = i; // implicit and always safe
o = "Now I have a machinegun ho-ho-ho"; // safe too
int j = o; // will not succeed if o is string
Analogy
Object variable is like a black box where you can put anything - music CD, pen, phone or banana. Not only you, but anyone can put something there. If the last thing which you put in a black box in the morning was a banana, can you come back in the evening and eat whatever you pull out from the black box? If you live alone, and room is closed, and your memory is excellent, and... then you can. And you will wonder why everybody checks their box's content before eating it. But if you are not live alone, or the room is not closed, or you can forget just once that you have put the phone into the box... Bon appetite
object
– Scorchero as int
doesn´t work becauseint
is a value-type which can´t be used in conjunction with anas
-cast. You may however useo as int?
. – Groundsi
variable aslong
to see it blowing up. Now do it correctly,int j = Convert.ToInt32(o);
– Sedliklong long
and then, when it's time to unbox, you just copy however many bytes you need to into the variable. And type checking could've just amounted totypecode1 <= typecode2
if you'd designed it right. – Africanize