Activator Activation Error .CreateInstance

I create an instance dynamically using Activator.CreateInstance. However, he says that the object cannot be null with every attempt. Paste the code below. Am I doing something wrong?

Is there a problem if

Activator.CreateInstance

replaces the usual switch / case statements to determine the type of an object at run time? Thank.

public abstract  class Base
{
    public abstract void Func();

}
public  class  Derived:Base
{
    public override void Func()
    {
        MessageBox.Show("Derived First");
    }
}

public class Derived2 : Base
{
    public override void Func()
    {
        MessageBox.Show("Derived Second");
    }
}

private void button1_Click(object sender, EventArgs e)
{
    // I was trying to make use of the overladed version 
    // where it takes the Type as parameter.
    BaseClass report = 
       (BaseClass) Activator.CreateInstance(Type.GetType("Derived")); 
    report.Func();
}
+5
source share
5 answers

From the parameter documentation typeName Type.GetType:

The assembled type name to receive. See AssemblyQualifiedName. If the type is in the current assembly or in Mscorlib.dll, it is enough to specify the type name qualifies in its namespace.

This means that you need to (at least) pass the namespace:

BaseClass report = (BaseClass) Activator.CreateInstance(Type.GetType("YourNamespace.Derived")); 
+3

, Type.GetType("Derived") null - Activator.CreateInstance.

Check:

  • Derived , ? , Assembly.GetType , Type.GetType()
  • ? , -
+3

Type.GetType("Derived"

Simeple

BaseClass report = (BaseClass) Activator.CreateInstance(Type.GetType("Derived"));

Base report = (Base)Activator.CreateInstance(typeof(Derived));
+3

GetType null. . .

. . AssemblyQualifiedName. Mscorlib.dll, , .

Add the namespace to "Derived", and if the class Derivedis in a different assembly, add ", assemblyname"to the end.


Please note that if you are not going to change the line you pass in GetType, then you can just use typeof(Derived)(although in this case with Activator.CreateInstance) not many points.

+1
source

In Runtime, your GetType call will return null. You should:

  • Your exact namespace
  • or use typeof
0
source

All Articles