Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an object of the type Object to another type using a Type object

Tags:

c#

.net

casting

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

like image 356
Nikola Stjelja Avatar asked Dec 14 '25 19:12

Nikola Stjelja


1 Answers

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.

like image 111
Jon Skeet Avatar answered Dec 16 '25 10:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!