Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call protected constructor in c#?

How to call protected constructor?

public class Foo{
  public Foo(a lot of arguments){}
  protected Foo(){}
}
var foo=???

This obviously fails test:

public class FooMock:Foo{}
var foo=new FooMock();
Assert(typeof(Foo), foo.GetType());
like image 454
Arnis Lapsa Avatar asked Dec 06 '10 11:12

Arnis Lapsa


People also ask

Can we use protected in constructor?

Modifiers public, protected and, private are allowed with constructors. We can use a private constructor in a Java while creating a singleton class.

When would you use a protected constructor?

A protected constructor means that only derived members can construct instances of the class (and derived instances) using that constructor. This sounds a bit chicken-and-egg, but is sometimes useful when implementing class factories. Technically, this applies only if ALL ctors are protected.

What happens if constructor of class A is made protected?

5. What happens if constructor of class A is made private? Explanation: If we make any class constructor private, we cannot create the instance of that class from outside the class.

What is the true about protected constructor?

What is true about protected constructor? Explanation: Protected access modifier means that constructor can be accessed by child classes of the parent class and classes in the same package.


1 Answers

Call parameterless protected/private constructor:

Foo foo = (Foo)Activator.CreateInstance(typeof(Foo), true);

Call non-public constructor with parameters:

  var foo = (Foo)typeof(Foo)
    .GetConstructor(
      BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance, 
      null, 
      new[] { typeof(double) }, 
      null
    )
    .Invoke(new object[] { 1.0 });

  class Foo
  {
     private Foo(double x){...}
  }
like image 174
Serj-Tm Avatar answered Sep 22 '22 13:09

Serj-Tm