views:

334

answers:

2

Having an object like this:

object integerObject=1;

And an object like this:

Type integerType=typeof(Int32);

How can be the integerType object used to cast the integerObject to the type of Int32

+5  A: 

The type of the object that integerObject refers to is already Int32, albeit the boxed version.

I suspect you have a third line of code which you haven't shown us, which is where you want to actually use the result of the operation you want us to help you with. Unfortunately, without that third line it's hard to know how to help.

The answer may involve generics. It may be as simple as a call to Convert.ChangeType - but without knowing the bigger picture, we can't really tell I'm afraid.

Jon Skeet
+3  A: 
int result = (int)Convert.ChangeType(integerObject, integerType);

Of course, its a largely useless exercise in this case, but if your "integerObject" was defined differently (a string perhaps) then it is a valid way to do things I guess.

You might be interested in this question too: http://stackoverflow.com/questions/555462/cast-with-gettype

Ch00k