Inheritance In C#

In this article I will explain about the concept of Inheritance in C#.
  • 3633

Introduction

The concept of inheritance is very simple in c#. Inheritance is one of the important concepts of object-oriented programming. Inheritance is the process by which we can inherits the properties or methods of base class into the derived class. It is done by putting a colon after the derived class when declaring the class and base class as follows:

public class A  (base class)

{

    public A() { }

}

 

public class B : A  (derived class : base class)

{

    public B() { }

}

Syntax

[Access Modifier] class ClassName : baseclassname

 

{

  

}

 

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ProgramCall

{

    class BaseClass

    {

       //Method to find Mul of Two numbers

        public int FindMul(int x, int y)

        {

            return (x * y);

        }

        //method to print given 2 numbers

        //When declared protected , can be accessed only from inside the derived class

        //cannot access  with the instance of  derived class

        protected void Print(int x, int y)

        {

            Console.WriteLine("First Number: " + x);

            Console.WriteLine("Second Number: " + y);

        }

         }

        class Derivedclass : BaseClass

        {

        public void Print3numbers(int x, int y, int z)

        {

            Print(x, y); //We can directly call baseclass members

            Console.WriteLine("Third Number: " + z);

        }

    }

    class MainClass

    {

        static void Main(string[] args)

        {

            //Create instance for derived class, so that base class members

            //This is possible because  derivedclass is inheriting base class

            Derivedclass of = new Derivedclass();

            of.Print3numbers(3,5,7); //Derived class internally calls base class method.

            int Mul = of.FindMul(3,5); //calling base class method with derived class instance

            Console.WriteLine("Mul : " + Mul);

            Console.Read();

        }

    }

}


The output of following program


Clipboard172.jpg

© 2020 DotNetHeaven. All rights reserved.