How to get a Type from a string

Asked

Viewed 48 times

0

For example, I want a string containing the information "System.Windows.Forms.Button" return a button object New Button(), would that be possible?

Note: Is tagged C# as it is easy to translate from C# to Visual Basic

1 answer

2


Use the function CreateInstance, informing all the way to the class:

var obj = Activator.CreateInstance(Type.GetType("System.Windows.Forms.Button"));

You can also use a cast in creating the variable for a class that you are sure is the parent of the one you are creating, for example:

var obj = (Control)Activator.CreateInstance(Type.GetType("System.Windows.Forms.Button"));

This way you can use the class functions Control easily.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.