TheBoxyBear
TheBoxyBear

Reputation: 403

Why can't Activator.CreateInstance<>() find an internal parameterless constructor?

I'm trying to create an instance of an object using Activator.CreateInstance<>(). The class used as a template has only one constructor which has no parameters but is internal. This shouldn't be an issue since that constructor is still accessible within the scope where CreateInstance is called. Yet, it throws the exception "No parameterless constructor defined for type...'.'". I made a new project to isolate it from any external factors and it still happens. Here are the classes in the test project

namespace Debug
{
    class Program
    {
        static void Main(string[] args)
        {
            TestClass test = System.Activator.CreateInstance<TestClass>();
        }
    }

    class TestClass
    { 
        internal TestClass() { }
    }
}

If I make the constructor public, the error doesn't occur, but why is that since Main should have access to it? What possible alternative could there be? I really can't just make the constructor public in the real project.

Another thing I tried was to move TestClass to the System namespace where Activator is located in case it's the CreateInstance method itself that doesn't have access to the constructor but the exception still gets thrown.

Upvotes: 0

Views: 1960

Answers (1)

Dave
Dave

Reputation: 3017

By Default Activator.CreateInstance only works with public constructors

However there is an overload that allows it to look for non-public constructors

public static object? CreateInstance (Type type, bool nonPublic);

https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance?view=netcore-3.1#System_Activator_CreateInstance_System_Type_System_Boolean_

Upvotes: 4

Related Questions