Instantiating Internal class with private constructor

EDIT: I hadn’t noticed that you mentioned that the type you’re trying to initialize is part of the .NET framework. I thought it was one of your own types, just referenced from elsewhere.

I would strongly urge you not to attempt this. Microsoft are perfectly at liberty to change or remove internal classes between framework releases – your code will be incredibly brittle if you rely on implementation details like this.

Change your design to avoid needing to do this.


Original answer:

Yes, you’d have to use reflection – like this:

using System;
using System.Reflection;

internal sealed class ABC
{
    private ABC(string password)
    {
        Console.WriteLine("Constructor called");
    }
}

public class Test
{
    static void Main()
    {
        ConstructorInfo ctor = typeof(ABC).GetConstructors
            (BindingFlags.Instance | BindingFlags.NonPublic)[0];

        ABC abc = (ABC) ctor.Invoke(new object[] { "test" });
    }
}

Note that violating access modifiers in this way requires the ReflectionPermissionFlag.MemberAccess permission. If you know there will be a static method called Create, you’d be better off invoking that via reflection:

using System;
using System.Reflection;

internal sealed class ABC
{
    private ABC(string password)
    {
        Console.WriteLine("Constructor called");
    }

    public static ABC Create(string password)
    {
        return new ABC(password);
    }
}

public class Test
{
    static void Main()
    {
        MethodInfo method = typeof(ABC).GetMethod("Create",
            BindingFlags.Static | BindingFlags.Public);

        ABC abc = (ABC) method.Invoke(null, new object[]{"test"});
    }
}

Leave a Comment