How to create an instance of a class object with an internal constructor through reflection?

Example:

class Program
{
    static void Main(string[] args)
    {
        var myClass = Activator.CreateInstance(typeof(MyClass));
    }
}

public class MyClass
{
    internal MyClass()
    {
    }
}

An exception:

System.MissingMethodException

There is no constructor without parameters for this object.

Decision:

var myClass = Activator.CreateInstance(typeof(MyClass), nonPublic:true);

I cannot understand why I cannot create an instance inside an assembly with an internal constructor. This constructor must be available inside the runtime assembly. It should work as a public for this assembly.

+5
source share
2 answers

This is not so impossible. you must say that this is not an audience.

var myClass = Activator.CreateInstance(typeof(MyClass), true);//say nonpublic
+16
source

The constructor inside your MyClass is internal. Try switching to public

public class MyClass
{
    public MyClass()
    {
    }
}

or

Pass true for CreateInstance

var myClass = Activator.CreateInstance(typeof(MyClass),true );
0

All Articles