What is a base class in C#?


When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the 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.

The following is the syntax of base class in C# −

<access-specifier> class <base_class> {
   ...
}

class <derived_class> : <base_class> {
   ...
}

Let us see an example −

Example

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();
      }
   }
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 20-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements