Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 225
Warlock Avatar asked Oct 08 '13 06:10

Warlock


1 Answers

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

var myClass = Activator.CreateInstance(typeof(MyClass), true);//say nonpublic
like image 133
Sriram Sakthivel Avatar answered Sep 28 '22 02:09

Sriram Sakthivel