What is Inheritance in C#?


Through Inheritance, you can define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time.

Inheritance is based on base class as well as the concept of derived class. A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces.

Let us see an example of base and derived class. Here, Shape is a base class whereas Rectangle is a derived class −

class Rectangle: Shape {
   // methods
}

The following is an example showing how to work with base class and derived class in Inheritance −

Example

 Live Demo

using System;

namespace InheritanceApplication {
   class Shape {
      public void setWidth(int w) {
         width = w;
      }
      public void setHeight(int h) {
         height = h;
      }
      protected int width;
      protected int height;
   }

   // Derived class
   class Rectangle: Shape {
      public int getArea() {
         return (width * height);
      }
   }

   class RectangleTester {
      static void Main(string[] args) {
         Rectangle Rect = new Rectangle();
         Rect.setWidth(5);
         Rect.setHeight(7);
         // Print the area of the object.
         Console.WriteLine("Total area: {0}", Rect.getArea());
         Console.ReadKey();
      }
   }  
}

Output

Total area: 35

Updated on: 20-Jun-2020

137 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements