Reputation: 10612
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
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