About
In this code snippet, we will take a look at the base keyword in C#.
The base keyword is used to get the members of the parent class. In this example, we will call the constructor from the parent class. By doing so we can avoid duplicating the code.
Let’s have a look at the code below to see how to use the base keyword.
Code:
using System; namespace baseClass { class Program { static void Main(string[] args) { MyClass MC = new MyClass(); MySecondClass MSC = new MySecondClass(); MC.MyMethod(); Console.WriteLine(""); MSC.MyMethod(); Console.ReadLine(); } } class MyClass { public void MyMethod() { Console.Write("Hello"); } } class MySecondClass : MyClass { public void MyMethod() { //Instead of duplicating code we can just call the method from the base class. base.MyMethod(); //Then we add the code specific for this version of the method. Console.Write(" World"); } } }