6

Example:

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

public class MyClass
{
    internal MyClass()
    {
    }
}

Exception:

System.MissingMethodException

No parameterless constructor defined for this object.

Solution:

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

I cannot understand, why I cannot create an instance inside the assembly with internal constructor. This constructor should be available inside the execution assembly. It should work like public for this assembly.

Warlock
  • 7,321
  • 10
  • 55
  • 75
  • 1
    possible duplicate of [Instantiating a constructor with parameters in an internal class with reflection](http://stackoverflow.com/questions/4077253/instantiating-a-constructor-with-parameters-in-an-internal-class-with-reflection) – CodingIntrigue Oct 08 '13 at 06:54
  • Maybe this will help: http://stackoverflow.com/questions/2654702/invoke-internal-extern-constructor-using-reflections – VikciaR Oct 08 '13 at 06:55

2 Answers2

18

It is not that impossible. you've to tell it is not a public.

var myClass = Activator.CreateInstance(typeof(MyClass), true);//say nonpublic
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
0

The constructor inside your MyClass is Internal try to change to public

public class MyClass
{
    public MyClass()
    {
    }
}

or

Pass true to CreateInstance

var myClass = Activator.CreateInstance(typeof(MyClass),true );
mpakbaz
  • 486
  • 1
  • 6
  • 20