Cuero Cuero - 3 months ago 12
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();
break;
case "PieSeries":
ans = new PieSeries();
break;
case "AreaSeries":
ans = new AreaSeries();
break;
case "BarSeries":
ans = new BarSeries();
break;
case "LineSeries":
ans = new LineSeries();
break;
}


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?
Thanks.

Answer

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").

Reference: http://msdn.microsoft.com/en-us/library/wccyzw83.aspx

UPDATE:

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

Comments