thatOneGuy
thatOneGuy

Reputation: 10612

Cast an object to a certain type based on a string

I have a 'basetype' object that I wish to cast to a specific type. I want to make this generic, so I wish to get the name of the object and cast it to a class with the same name. Something like so :

string name = baseObj.name;

var baseObj = baseObj as getClassFor(name);

I have found the Activator but I Activator.CreateInstance(), i dont think, is what I need.

My question is, how do I cast an object to a certain type based on a string?

Upvotes: 0

Views: 108

Answers (1)

George Chondrompilas
George Chondrompilas

Reputation: 3237

As casting is mostly a compile time thing, you can't cast to a specific Type based on a string, so you have to use the dynamic keyword.

var t= Type.GetType(baseObj.name); //This should contain the correct namespace too. ex. "MyNamespace.SpecificClass"
dynamic specificObj = Convert.ChangeType(baseObj, t);
specificObj.SpecificMethod();

Upvotes: 1

Related Questions