find and solve || findandsolve.com
Please wait.....

Inheritance in C# and .NET

Inheritance in c# is a process in which one object acquires all the properties. Its behaviors of its parent object automatically. In such a way, we can reuse, modify or extend the attributes and behaviors which is defined in other class.

Which class inherits the members of another class is called the derived class  whose class members are inherited is called base class.The derived class is the specialized class for the base class.

Inheritance (Derived and Base Class)

  • Derived Class (child) - the class that inherits from another class
  • Base Class (parent) - the class being inherited from


C# Single Level Inheritance Example: Inheriting Fields

When one class inherits from another class, it is known as single-level inheritance. For example.

   using System;  

   public class EmployeeInfo
    {
       public float Salary = 200000;
   }
   public class Employee: EmployeeInfo
   {
       public float OT = 40000;
   }
   public class TestInheritance{
       public static void Main(string[] args)
        {
            Employee objEmployee = new Employee();
            Console.WriteLine("Salary: " + objEmployee.Salary);
            Console.WriteLine("Bonus: " + objEmployee.OT);
        }
    }  

Output

Salary: 200000

Bonus: 40000

C# Single Level Inheritance Example: Inheriting Methods

   using System;  

   public class DOG
    {
       public void eat() { Console.WriteLine("Eating..."); }
   }
   public class COW: DOG
   {
       public void bark() { Console.WriteLine("Barking..."); }
   }
   public class InheritanceExample{
       public static void Main(string[] args)
        {
            COW objCow = new COW();
            objCow.eat();
            objCow.bark();
        }
    }  

Output

Eating...

Barking...


C# Multi Level Inheritance Example

When one class inherits from another class which is further inherited by another class, it is known as a multi-level inheritance in C# programming language. In C#, Inheritance is transitive so the last derived class acquires all the members of all its base classes.

   using System;  

   public class DOG
    {
       public void eat() { Console.WriteLine("Eating..."); }
   }
   public class COW: DOG
   {
       public void bark() { Console.WriteLine("Barking..."); }
   }
  public class SmallDOG : COW
   {
       public void weep() { Console.WriteLine("Weeping..."); }
   }
   public class InheritanceExample{
       public static void Main(string[] args)
        {
            SmallDOG objSmallDOG = new SmallDOG();
            objSmallDOG.eat();
            objSmallDOG.bark();
      objSmallDOG.weep();
        }
    }  

Output

Eating...

Barking...

Weeping...


The sealed Keyword

If you don't want other classes to inherit from a class, use the sealed keyword:

sealed class Vehicle 

{
  ...
}
class Car : Vehicle
{
  ...
}

Output

'Car': cannot derive from sealed type 'Vehicle'