Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting using System.Type - c#

Tags:

c#

casting

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

like image 913
maxp Avatar asked Dec 09 '11 16:12

maxp


3 Answers

Have a look at:

var foo = Convert.ChangeType(o, typeof(string))
like image 139
Francois Avatar answered Nov 07 '22 06:11

Francois


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.

like image 28
SLaks Avatar answered Nov 07 '22 04:11

SLaks


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

like image 1
Jeffrey Zhao Avatar answered Nov 07 '22 06:11

Jeffrey Zhao