Reputation: 3018
I have an existing base type and I would like to cast it to a derived type base upon the name of the type as a string, so something like this:
public void DoStuffInDerivedType(string derivedName) {
(base as Type.GetType(derivedName)).DoThisThing();
}
I'm pretty sure this can't be done but would be good to know for sure. Thanks
EDIT: I understand that I could construct the object using reflection from the type name but I want use an existing object. And also I know this is generally a bad idea. However I wanted to use this for a SpecFlow BDD Feature.
Upvotes: 20
Views: 30403
Reputation: 443
I'll repeat the advice that you probably don't need to do this, but because I have done this operation before:
Convert.ChangeType(ItemToCast, Type.GetType(stringNameOfType)))
Should work for you.
Upvotes: 34
Reputation: 19064
I don't think you need to cast it to the derived type. You should be able to cast it to the base type and use the shared interface (be it a base class or literal Interface) to perform whatever you want done.
If not, consider adding the behavior as an interface requirement so you can do it that way.
Finally: the one possibility where you'd need to do it this way is if you're overriding the casts...in which case I'm almost certain you can't do this without some heavy duty reflection.
Upvotes: 3