Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast to a type from the type name as a string

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.

like image 417
jolySoft Avatar asked Mar 17 '16 16:03

jolySoft


People also ask

How do you use type as variables?

For example: Type intType = typeof(Int32); object value1 = 1000.1; // Variable value2 is now an int with a value of 1000, the compiler // knows the exact type, it is safe to use and you will have autocomplete int value2 = Convert.


2 Answers

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.

like image 154
Tyler H Avatar answered Oct 13 '22 20:10

Tyler H


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.

like image 38
Chris Pfohl Avatar answered Oct 13 '22 22:10

Chris Pfohl