Is this possible to do?

  • Thread starter Thread starter Sahil Malik
  • Start date Start date
S

Sahil Malik

Lets say .. I get a string ..
"System.Windows.Forms.TextBox"

Can I instantiate an instance of that .. given that the ONLY information I
have is that string above i.e. classname?

To make things easy, such a classname is in GAC.

- Sahil Malik
http://codebetter.com/blogs/sahil.malik/
 
That's where reflection comes in:

using System.Reflection;

string className = "System.Windows.Forms.TextBox";

Type classType = Type.GetType(className, false);
ConstructorInfo constructor = classType.GetConstructor(new Type[0]); //
Assuming you want to use the default constructor
object newInstance = constructor.Invoke(new object[0]); // Again assuming
you're using the default constructor

Now you can cst newInstance to the required object to access the methods /
properties you need.

Hope this helps.

Jako Menkveld
 
Back
Top