Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 991
Tom Robinson Avatar asked Nov 27 '08 15:11

Tom Robinson


People also ask

How do you call a base class constructor?

You can call the base class constructor from the child class by using the super() which will execute the constructor of the base class.

Does base class constructor get called automatically?

Whenever the derived class's default constructor is called, the base class's default constructor is called automatically. To call the parameterized constructor of base class inside the parameterized constructor of sub class, we have to mention it explicitly.

Is it possible to inherit the constructors of its base class?

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.

How would you call the base class constructor from the derived class in C #?

We have to call constructor from another constructor. It is also known as constructor chaining. When we have to call same class constructor from another constructor then we use this keyword. In addition, when we have to call base class constructor from derived class then we use base keyword.


2 Answers

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).

like image 94
Jon Skeet Avatar answered Sep 17 '22 15:09

Jon Skeet


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

like image 35
Johannes Schaub - litb Avatar answered Sep 20 '22 15:09

Johannes Schaub - litb