maxp
maxp

Reputation: 25171

Casting using System.Type - c#

Is it possible to cast an object to a desired type using System.Type? as the reference?

I had a search and the general consensus was no, although I was hoping there may be some aids introduced in C# 4.0 that could help me.

I.e. the below will not work, but the pseudocode is what I would like.

object o = null;
var t = typeof(string);
...
string foo = (t)o;

Edit: I need use XmlSerializer to reconstruct / deserialize to the type stored in t

Upvotes: 16

Views: 18820

Answers (4)

Francois
Francois

Reputation: 10978

Have a look at:

var foo = Convert.ChangeType(o, typeof(string))

Upvotes: 26

Felice Pollano
Felice Pollano

Reputation: 33272

I guess you are looking for something like System.ChangeType(). This works if the type implement IConvertible, and if it is convertible to the desired type ( of course this is not a cast )

Upvotes: 0

Jeffrey Zhao
Jeffrey Zhao

Reputation: 5023

No need to cast. The object doesn't change, your type of references (variables) changes when "casting".

Upvotes: 1

SLaks
SLaks

Reputation: 888223

That doesn't make sense.

Casting doesn't change an object at all; it just lets you use the object as the given type at compile-time.
If you don't know what type you're casting it to at compile-time, the cast is useless, since it wouldn't let you do anything with the casted expression.

Upvotes: 3

Related Questions