tags:

views:

285

answers:

1

Is there a way in C# to cast an object based on a string?

Example,

String typeToCast = control.GetType().Name;

Button b = (typeToCast)control;
+3  A: 

No, you can't do that. Also, what would you achieve, as you have to assign it to "static" type, in your case, it's Button - So why not just cast it normally:

Button b = (Button)control;

You can hovewer, check if your control is of a type:

Type t = TypeFromString(name);
bool isInstanceOf = t.IsInstanceOfType(control);

Edit: To create an object without having it type at compile time, you can use Activator class:

object obj = Activator.CreateInstance(TypeFromString(name));
Button button = (Button)obj; //Cast to compile-time known type.
Ravadre
Because I want to create objects dynamically based on a specified type. Your taking the example to literally
Sir Psycho
Well then, you should ask if you can create an object, having it's type's name - yes you can.
Ravadre