How can I force the base constructor to be called in C#?

I have a BasePage class which all other pages derive from:

public class BasePage

This BasePage has a constructor which contains code which must always run:

public BasePage()
    // Important code here

I want to force derived classes to call the base constructor, like so:

public MyPage
    : base()
    // Page specific code here

How can I enforce this (preferably at compile time)?


The base constructor will always be called at some point. If you call this(...) instead of base(...) then that calls into another constructor in the same class - which again will have to either call yet another sibling constructor or a parent constructor. Sooner or later you will always get to a constructor which either calls base(...) explicitly or implicitly calls a parameterless constructor of the base class.

See this article for more about constructor chaining, including the execution points of the various bits (such as variable initializers).

The base class constructor taking no arguments is automatically run if you don't call any other base class constructor taking arguments explicitly.

The base class constructor is always called, even if you don't call it explicitly. So you don't need to do any extra work to make sure that happens.

One of the base constructors always needs to be called, and the default one is called when the base constructor is not explicitly stated.

Edit: rephrased for clarity.

Need Your Help

What's a reasonable amount of memory for a .NET application?

memory clr

I've had a couple of complaints that one of our managed apps is using 20-25Mb of RAM. I normally push back and say that memory's cheap; get over it.

How is it possible to sell code written in an interpreted language?


It seems to me that if you are writing in an interpreted language that it must be difficult to sell software, because anyone who buys it can edit it/change it/resell it without much difficulty.