Razor
Razor

Reputation: 17498

Dynamic casting based on a string

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

Example,

String typeToCast = control.GetType().Name;

Button b = (typeToCast)control;

Upvotes: 3

Views: 3997

Answers (2)

Riversoul
Riversoul

Reputation: 71

Yes you can but you should not.

Csharp

string value = "2.5";
object typedObject;
typedObject = Convert.ChangeType(value, Type.GetType("System.Double"));

Vbnet

Dim value As String = "2.5"
Dim typedObject As Object
typedObject = Convert.ChangeType(value, Type.GetType("System.Double"))

Upvotes: 7

Marcin Deptuła
Marcin Deptuła

Reputation: 11957

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.

Upvotes: 3

Related Questions