Search code examples
c#reflectioncompiler-optimizationinternal

How to prevent C# compiler from removing internal constructor


I have a public class with 2 constructors: The default (without parameters), which is internal, and a different one, which is public. The default constructor calls the other one with some default values.

I call the internal constructor using reflection, so it's not used anywhere in the assembly statically (only by reflection).

When I make the reflection call, I'm getting:

System.MissingMethodException
    Message=No parameterless constructor defined for this object.

I know of two workarounds:

  1. Make the constructor public (but I don't want the users of this assembly to use it).
  2. Call the constructor from some public method (I have many classes like this one, so I don't want to write a lot of this ugly useless code).

Any better solutions to this problem?

It's worth mentioning that if the default constructor is public, I don't get that exception.

Thanks,

Boaz.


Solution

  • The constructor is not removed, probably in the search of your constructor you should specify the flag BindingFlag.NonPublic.

        class xxx
        {
            private xxx() :
                this(10)
            {
            }
    
            public xxx(int value)
            {
                Console.WriteLine(value);
            }
        }
    
        static void Main(string[] args)
        {
            Activator.CreateInstance(typeof(xxx), true);
            Console.ReadLine();
        }
    

    Activator.CreateInstance have an overload with a boolean where you can specify if you want to call a non public constructor.

    public static Object CreateInstance(
        Type type,
        bool nonPublic
    )
    

    Activator.CreateInstance(type, true) will call the constructor both if it is public or private\internal\protected.