Click here to Skip to main content
15,896,201 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi All,


Boxing:
int a=4;
object Obj=a;

Unboxing

int j=(int)obj;

Can anybody explain me why do we write int in the braces and why can not we write convert.Toint32 instead of writing (int)


Thanx in Advance
Posted
Comments
Sergey Alexandrovich Kryukov 25-Jul-12 2:06am    
"Can anyone explain" is not a valid question. This matter is not quite trivial, but at the same time it's very elementary, related to some very basic CLR knowledge every .NET developer should have. So, how could you be in doubt if anyone could answer? And you could get the answer by yourself if you did one of the following (or both): 1) disassembled the code (some IL knowledge required), 2) read the manuals with more attention.
--SA

You can.
It's just shorter and clearer to use the cast.
C#
object o = 123;
int i = (int) o;
int j = Convert.ToInt32(o);
The two statements are functionally equivalent, but the former is easier to read, particularly when the expression is more complicated than a simple object.
 
Share this answer
 
Yes, of course. Because the compile-time type of obj is System.Object. It is not known that the actual run-time type of the referenced object at the moment of assignment is the boxed System.Int32. So, explicit type cast shows that this is the cast operation which may or may not be successful.

And of course, the compiler cannot trace the code and determine that the initialization of the object variable or the previous assignment was to the int object, or even any boxed type. From your code sample this is not so obvious, but it's pretty easy to write some code and proof that it is theoretically impossible to determine the run-time type of the obj referenced object statically (during compilation). (One idea: you can pass the reference to some method using pseudo-random number generator and assigning objects of different types to the variable.) This way, the compiler cannot know actual run-time type of the operation.

If the cast operator tries to cast the object reference to some type which is not assignment compatible to the run-time type of the referenced object, this cast operation with throw a cast exception. In this respect, it does not matter if the cast involves unboxing or not.

—SA
 
Share this answer
 

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