C# Class Inheritance


Classes (but not structs) support the concept of inheritance. A class that derives from the base class automatically has all the public, protected, and internal members of the base class except its constructors and destructors.

A class can inherit from another class to extend the original class.

Inheriting from a class lets you reuse the functionality in that class.

A class can inherit from only a single class.


The general form of a class declaration that inherits a base class:

class derived-class-name : base-class-name {
    // body of class


In this example, we start by defining a class called Shape:

public class Shape { 
  public string Name; 

Next, we define classes called Circle and Rectangle, which will inherit from Shape. They get everything an Shape has, plus any additional members that they define:

public class Circle : Shape   // inherits from Shape 
{ //  w w w .  j  av a  2s.  c o  m
  public long Radius; 

public class Rectangle : Shape   // inherits from Shape 
  public decimal Width; 

Here's how we can use these classes:

Circle myCircle = new Circle { Name="Circle", 
                         Radius=1000 }; 
// www .j ava  2s. c  om
Console.WriteLine (myCircle.Name);       
Console.WriteLine (myCircle.Radius); 

Rectangle myRect = new Rectangle { Name="Rectangle",                                                    
                            Width=250000 };                                                 

Console.WriteLine (myRect.Name);                                              
Console.WriteLine (myRect.Width);   

The subclasses, Circle and Rectangle, inherit the Name property from the base class, Shape.


A subclass is also called a derived class. A base class is also called a superclass.

Home »
  C# Tutorial »
    Custom Types »

C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor