Click here to Skip to main content
12,752,054 members (29,399 online)
Rate this:
Please Sign up or sign in to vote.
See more: C#3.5
Hi All,

int a=4;
object Obj=a;


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 24-Jul-12 20:51pm
"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.
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

You can.
It's just shorter and clearer to use the cast.
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.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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.


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

    Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170217.1 | Last Updated 25 Jul 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100