What is Inheritance in C#?

CsharpProgrammingServer Side Programming

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
raja
Published on 09-Aug-2018 08:48:15
Advertisements