Home » .Net

Inheritance in C# with Example

In this article, we are going to learn about Inheritance in C#.net: What is Inheritance, what are its properties? How can we implement Inheritance? Learn everything about Inheritance with Example.
Submitted by IncludeHelp, on April 03, 2018

As we know that, inheritance is one of the most important concepts object-oriented programming language. Inheritance provides the mechanism to create a new class with the feature of an existing class. Using Inheritance we can reuse code functionality so that we can utilize code implementation time.

When we create a new class, instead of writing all data member and methods. Programmers create a new class and inherit all data member and methods of existing class.

In case of inheritance, A newly created class is known as a child or derived or subclass. And Existing class by using that we create a new class is known as parent or base or superclass.

Inheritance in C# with Examples

In above example, there are two classes A and B. A is parent class and B is a child class. B can reuse all data member and methods of class A.

A class can also be derived more than one class; it means a derived can inherit the data member or methods from more than one class.

Syntax of base and derived class:

    <access_specifier> class <parent_class>
    {
	    ...
    }

    class <child_class> : <parent_class>
    {
	    ...
    }

C# program to demonstrate an Example on Inheritance

using System;
using System.Collections;
namespace ConsoleApplication1
{
    class A
    {
        protected int Num1;
        protected int Num2;

        public void setVal(int n1, int n2)
        {
            Num1 = n1;
            Num2 = n2;
        }
    }

    class B : A
    {
        public int getSum()
        {
            return (Num1 + Num2);
        }
    }
         
    class Program
    {
        static void Main()
        {
            B ob = new B();

            ob.setVal(10,20);

            Console.WriteLine("Get Sum : " + ob.getSum());
        }
    }
}

Output

Get Sum : 30


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.