Dynamic row-based casting

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

Example

String typeToCast = control.GetType().Name;

Button b = (typeToCast)control;
+3
source share
2 answers

No, you cannot do this. Also, what would you achieve, since you need to assign it to a “static” type, in your case, Button - so why not just say it normally:

Button b = (Button)control;

You can use, check if your control type is of type:

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

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

object obj = Activator.CreateInstance(TypeFromString(name));
Button button = (Button)obj; //Cast to compile-time known type.
+3
source

Yes you can, but you shouldn't.

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"))
+7
source

Source: https://habr.com/ru/post/1717303/


All Articles