Cuero Cuero - 1 year ago 73
C# Question

How to invoke Constructors by String in C# (i.e. by Reflection)?

I use the Chart class WPFToolKit and I want to invoke Construtors by String to short the code below

switch (node.Attributes["type"].Value)
case "ColumnSeries":
ans = new ColumnSeries();
case "PieSeries":
ans = new PieSeries();
case "AreaSeries":
ans = new AreaSeries();
case "BarSeries":
ans = new BarSeries();
case "LineSeries":
ans = new LineSeries();

After searching I find the code below:

Type type = Type.GetType(node.Attributes["type"].Value);
Console.WriteLine(type == null);
ConstructorInfo ctor = type.GetConstructor(new Type[] { });
object instance = ctor.Invoke(new object[]{});

But strangely, the type is always null and I don't why. Could anyone tell me that?

Answer Source

If your class has a public default constructor, you can use Activator.CreateInstance(Type.GetType("your type")). But make sure you give it full type name (with namespace like "System.Int64").



If the type is in another assembly, refer to this SO question to know how to get the type.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download