How to Call Constructor of Base Class From the Constructor of Child Class in C#
-
Call the Default Constructor of Base Class From the Constructor of Child Class in
C#
-
Pass Arguments to the Constructor of Base Class From the Constructor of Child Class With the
base
Keyword inC#
This tutorial will discuss methods to call the base class’s constructor from the constructor of child class in C#.
Call the Default Constructor of Base Class From the Constructor of Child Class in C#
In C#, when we create an instance of the child class, the base class’s default constructor automatically gets invoked by the compiler. This phenomenon is shown in the code example below.
using System;
namespace call_constructor_of_base_class {
public class baseClass {
public baseClass() {
Console.WriteLine("This is the Base Class");
}
}
public class childclass : baseClass {
public childclass() {
Console.WriteLine("This is the Child Class");
}
}
class Program {
static void Main(string[] args) {
childclass c = new childclass();
}
}
}
Output:
This is the Base Class
This is the Child Class
In the above code, the baseClass
is the base class, and the childclass
is the child class that inherits baseClass
. When we create an instance of the child class childclass
, the default constructor of the baseClass
automatically gets called by the compiler. The constructor of the baseClass
gets executed before the constructor of childclass
. This method cannot be used to pass arguments to the base class’s constructor from the child class’s constructor.
Pass Arguments to the Constructor of Base Class From the Constructor of Child Class With the base
Keyword in C#
If we want to pass arguments to the base class’s constructor from the constructor of the child class, we have to use the base
keyword in C#. The base
keyword specifies which constructor of the base class should be called when an instance of the child class is created. The following code example shows us how we can pass arguments to the base class’s constructor from the constructor of the child class with the base
keyword in C#.
using System;
namespace call_constructor_of_base_class {
public class baseClass {
public baseClass() {
Console.WriteLine("This is the Base Class");
}
public baseClass(int x) {
Console.WriteLine("The Child class passed {0} to the Base Class", x);
}
}
public class childclass : baseClass {
public childclass(int a) : base(a) {
Console.WriteLine("This is the Child Class");
}
}
class Program {
static void Main(string[] args) {
childclass c = new childclass(10);
}
}
}
Output:
The Child class passed 10 to the Base Class
This is the Child Class
In the above code, we pass 10 to the parameterized constructor of the base class baseClass
from the constructor of the child class childclass
.
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn