Base Keyword in C#

In this article I will explain about base keyword in C#.
  • 4580

Introduction

The concept of base keyword is very simple in c#. The base keyword is used when we want to access members and functionalities of the base class, from within a derived class. In the following example, both the base class, Owner, and the derived class, Employee, have a method named info. By using the base keyword, it is possible to call the info method on the base class, from within the derived class.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace this_example

{

    public class Owner

    {

        protected string pinname = "78";

        protected string name = "rahul";

 

        public virtual void Info()

        {

            Console.WriteLine("Name: {0}", name);

            Console.WriteLine("pinname: {0}", pinname);

        }

    }

    class Employee : Owner

    {

        public string id = "ABC567";

 

        public override void Info()

        {

            // Calling the base class GetInfo method:

            base.Info();

            Console.WriteLine("Employee ID: {0}", id);

        }

    }

 

    class TestClass

    {

        public static void Main()

        {

            Employee E = new Employee();

            E.Info();

            Console.ReadLine();

        }

    }

}

 

The output of following program

Clipboard162.jpg

© 2020 DotNetHeaven. All rights reserved.