How to fire a constructor from a type object

  • Thread starter Thread starter Marco
  • Start date Start date
M

Marco

Howdy!
Given that:

Type type = Type.GetType("System.Windows.Forms.Button");

Question: How do I obtain a Button object by only knowing
the type object. In other words, how do I fire the
constructor of a type object (Button(), in this case) ???

Thank you and God bless.

_____
Marco
 
Marco said:
Howdy!
Given that:

Type type = Type.GetType("System.Windows.Forms.Button");

Question: How do I obtain a Button object by only knowing
the type object. In other words, how do I fire the
constructor of a type object (Button(), in this case) ???

Thank you and God bless.
Basically:

ConstructorInfo i = type.GetConstructor(Type.EmptyTypes);

object o = i.Invoke(null);

o should contain the object created by the constructor. Other methods exist,
of course, including Activator.CreateInstance(), which are probably eaiser
to use unless you need to verify a certain constructor exists.
 
of course, it would help if I mentioned how to use
Activator.CreateInstance...
in this case, a simple
object o = Activator.CreateInstance(type);
should create an instance of your type, assuming no strange circumstances.
 
Marco, there are a couple of ways to do this. One way is to use the
GetConstructor(s) methods off of the Type object. You can then call
Invoke() on the ConstructorInfo object.
 
Back
Top