10 December 2012

What is Inheritance in C#


Creating a new class from existing class is called as inheritance. 


    //All the car properties can be used by the supercar
    class SuperCar : car
    {


    }


When a new class needs same members as an existing class, then instead of creating those members again in new class, the new class can be created from existing class, which is called as inheritance.


Main advantage of inheritance is reusability of the code.


During inheritance, the class that is inherited is called as base class and the class that does the inheritance is called as derived class and every non private member in base class will become the member of derived class.

If you want the base class members to be accessed by derived class only , you can apply access modifier Protected to the base class member.

There are 5 Different types of inheritance.


Syntax
[Access Modifier] class ClassName : baseclassname

{ 


}

C# Inheritance Example


//Example program demonstrates singular inheritance
using System;

namespace ProgramCall
{
    class BaseClass
    {


        //Method to find sum of give  2 numbers
        public int FindSum(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
            // can also  be accessed

            //This is possible because  derivedclass is inheriting base class

            Derivedclass instance = new Derivedclass();

            instance.Print3numbers(30, 40, 50); //Derived class internally calls base class method.
            int sum = instance.FindSum(30, 40); //calling base class method with derived class instance
            Console.WriteLine("Sum : " + sum);


            Console.Read();
        }

    }
}

Output

First Number: 30
Second Number: 40
Third Number: 50
Sum : 70