Is there a way in C# to cast an object based on a string?
Example,
String typeToCast = control.GetType().Name;
Button b = (typeToCast)control;
Is there a way in C# to cast an object based on a string?
Example,
String typeToCast = control.GetType().Name;
Button b = (typeToCast)control;
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.