Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent a base constructor from being called by an inheritor in C#?

I've got a (poorly written) base class that I want to wrap in a proxy object. The base class resembles the following:

public class BaseClass : SomeOtherBase  {    public BaseClass() {}     public BaseClass(int someValue) {}     //...more code, not important here } 

and, my proxy resembles:

public BaseClassProxy : BaseClass {   public BaseClassProxy(bool fakeOut){} } 

Without the "fakeOut" constructor, the base constructor is expected to be called. However, with it, I expected it to not be called. Either way, I either need a way to not call any base class constructors, or some other way to effectively proxy this (evil) class.

like image 758
casademora Avatar asked Oct 01 '08 19:10

casademora


People also ask

Can constructor of base class be inherited?

In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.

Does inheritance inherit constructors?

Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

How constructors are being called in inheritance?

For multiple inheritance order of constructor call is, the base class's constructors are called in the order of inheritance and then the derived class's constructor.

How do you override a base class constructor?

No, you can't override the constructor. If you take a look at the basic syntax of a constructor, it should have the same name as the class you are writing it for.


1 Answers

There is a way to create an object without calling any instance constructors.

Before you proceed, be very sure you want to do it this way. 99% of the time this is the wrong solution.

This is how you do it:

FormatterServices.GetUninitializedObject(typeof(MyClass)); 

Call it in place of the object's constructor. It will create and return you an instance without calling any constructors or field initializers.

When you deserialize an object in WCF, it uses this method to create the object. When this happens, constructors and even field initializers are not run.

like image 198
Neil Avatar answered Oct 11 '22 12:10

Neil