This keyword is used in constructors (in constructor initializers). A derived class
constructor is required to call the constructor from its base class
.
In a C# program, when the default constructor isn't present, the custom base constructor can (with base) be referenced. This can eliminate duplicated code.
class
exampleThe program uses a base class
and a derived class
. Both of the classes use a non-default, parameterful constructor.
class
must use a base constructor initializer, with the base keyword, in its constructor declaration.Class
A and class
B have constructors. Class
A is the parent or base class
for class
B, which is referred to as the derived class
.class
B derives from class
A. We use a colon character to indicate inheritance.class
B calls into the constructor of class
A using base initializer syntax.using System; public class A // This is the base class. { public A(int value) { // Executes some code in the constructor. Console.WriteLine("Base constructor A()"); } } public class B : A // This class derives from the previous class. { public B(int value) : base(value) { // The base constructor is called first. // ... Then this code is executed. Console.WriteLine("Derived constructor B()"); } } class Program { static void Main() { // Create a new instance of class A, which is the base class. // ... Then create an instance of B. // ... B executes the base constructor. A a = new A(0); B b = new B(1); } }Base constructor A() Base constructor A() Derived constructor B()
Let us compare base and this. In a derived class
, the base and this keywords can reference members. These keywords eliminate confusion as to which member we want.
class
, we can use a "base" expression to directly access the base class
.using System; class Net { public int _value = 6; } class Perl : Net { public new int _value = 7; public void Write() { // Show difference between base and this. Console.WriteLine(base._value); Console.WriteLine(this._value); } } class Program { static void Main() { Perl perl = new Perl(); perl.Write(); } }6 7
We use these keywords to resolve ambiguous things. If the base and this keywords were removed, the compiler would not know the difference between _value fields.
class
hierarchy. With them, we access members from a targeted class
.There is another keyword that can be used in a constructor initializer. You can use this()
with the argument list of another constructor declaration in the same type.
class
, not the parent class
.The base initializer is similar to the this
-initializer in constructors. We can specify the base initializer when deriving from types with non-default constructors.