C# Base Keyword

C# Code Snippets base keyword
Share:

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");
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger