Inheritance in C# with Example

In this article, we will find out about Inheritance in C#.net: What is Inheritance, what are its properties? How might we actualize Inheritance? Get the hang of everything about Inheritance with Example.

As we realize that, inheritance is one of the most significant ideas object-arranged programming language. Inheritance gives the system to make another class with the element of a current class. Utilizing Inheritance we can reuse code usefulness with the goal that we can use code execution time.

At the point when we make another class, rather than composting all information part and strategies. Software engineers make another class and acquire all information part and techniques for an existing class.

If there should be an occurrence of inheritance, A recently made class is known as a kid or determined or subclass. What’s more, Existing class by utilizing that we make another class is known as parent or base or superclass.

Inheritance in C# with Example

In the above example, there are two classes A and B. An is parent class and B is a kid class. B can reuse all information part and techniques for class A.

A class can likewise be inferred more than one class; it implies a determined can acquire the information part or strategies from more than one class.

Syntax of base and determined class:

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

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

C# program to exhibit 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

Leave a Comment

error: Alert: Content is protected!!