Cuero
Cuero

Reputation: 1209

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.

Upvotes: 3

Views: 1349

Answers (2)

prashanth
prashanth

Reputation: 2099

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.

Upvotes: 6

Petar Ivanov
Petar Ivanov

Reputation: 93080

Type.GetType expects a assembly-qualified name:

Here is the documentation about it: "The assembly-qualified name of the type to get. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace."

This includes the namespace and the assembly of the type. For example the assembly qualified name for the string class is something like this:

"System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"

(I got that with Console.WriteLine(typeof(string).AssemblyQualifiedName);)

Upvotes: 2

Related Questions