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)?
You can call the base class constructor from the child class by using the super() which will execute the constructor of the base class.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With