C# - Inheritance

Inheritance in C#

Inheritance is one of the core pillars of Object-Oriented Programming (OOP) in C#. It enables new classes to be based on existing classes, promoting code reuse, extensibility, and a clear hierarchical relationship between types. This detailed guide covers everything you need to know about inheritance in C#, from basic concepts to advanced usage, including examples and best practices.

1. Introduction to Inheritance

Inheritance allows a class (called the derived class or child class) to inherit members (fields, properties, methods, events) from another class (called the base class or parent class). This relationship models an "is-a" association β€” the derived class is a specialized version of the base class.

1.1 Why Use Inheritance?

  • Code Reuse: Avoid rewriting common functionality by inheriting it from a base class.
  • Extensibility: Extend or modify behavior without changing the original class.
  • Polymorphism: Use a base class reference to refer to derived class objects for flexible code.
  • Logical Hierarchies: Represent real-world relationships naturally.

1.2 Real-World Example

Consider a base class Animal and derived classes like Dog and Cat. Dogs and cats share common animal properties (like breathing and eating) but also have specialized behaviors.

2. Basic Syntax of Inheritance in C#

Inheritance is implemented using the colon (:) syntax after the derived class name.

public class Animal
{
    public void Eat()
    {
        Console.WriteLine("Eating...");
    }
}

public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Barking...");
    }
}

In this example, Dog inherits Eat() method from Animal, and also has its own Bark() method.

2.1 Creating and Using Derived Class Objects

Dog myDog = new Dog();
myDog.Eat();  // Output: Eating...
myDog.Bark(); // Output: Barking...

3. Types of Inheritance in C#

C# supports several inheritance patterns:

3.1 Single Inheritance

One derived class inherits from one base class.

class Vehicle
{
    public void Start() => Console.WriteLine("Vehicle started.");
}

class Car : Vehicle
{
    public void Drive() => Console.WriteLine("Car is driving.");
}

3.2 Multilevel Inheritance

A class derives from a derived class.

class Animal
{
    public void Eat() => Console.WriteLine("Eating...");
}

class Mammal : Animal
{
    public void Walk() => Console.WriteLine("Walking...");
}

class Dog : Mammal
{
    public void Bark() => Console.WriteLine("Barking...");
}

3.3 Hierarchical Inheritance

Multiple classes inherit from a single base class.

class Animal
{
    public void Eat() => Console.WriteLine("Eating...");
}

class Dog : Animal
{
    public void Bark() => Console.WriteLine("Barking...");
}

class Cat : Animal
{
    public void Meow() => Console.WriteLine("Meowing...");
}

3.4 Multiple Inheritance (via Interfaces)

C# does not support multiple class inheritance but allows multiple interface inheritance.

interface IWalkable
{
    void Walk();
}

interface ISwimmable
{
    void Swim();
}

class Amphibian : IWalkable, ISwimmable
{
    public void Walk() => Console.WriteLine("Walking...");
    public void Swim() => Console.WriteLine("Swimming...");
}

4. Access Modifiers and Inheritance

Access modifiers control visibility of class members in inheritance scenarios.

Modifier Access within Derived Class Access Outside Assembly
publicYesYes
privateNoNo
protectedYesNo
internalYes (if same assembly)No
protected internalYesYes if same assembly

4.1 Protected Members

protected members are accessible only within the class and its derived classes, which is key for inheritance encapsulation.

public class Animal
{
    protected string name;

    protected void SetName(string n)
    {
        name = n;
    }
}

public class Dog : Animal
{
    public void Initialize(string dogName)
    {
        SetName(dogName);
        Console.WriteLine($"Dog's name is {name}");
    }
}

5. Constructors and Inheritance

Derived classes do not inherit constructors but can call base class constructors explicitly using the base keyword.

5.1 Base Constructor Call

public class Person
{
    public string Name;

    public Person(string name)
    {
        Name = name;
    }
}

public class Employee : Person
{
    public int EmployeeId;

    public Employee(string name, int id) : base(name)
    {
        EmployeeId = id;
    }
}

5.2 Constructor Execution Order

When creating an object of a derived class:

  • Base class constructor runs first.
  • Then derived class constructor executes.

6. Method Overriding and Polymorphism

Inheritance allows derived classes to modify behavior of base class methods via overriding.

6.1 Virtual Methods

Base class methods declared with virtual can be overridden.

public class Animal
{
    public virtual void Speak()
    {
        Console.WriteLine("Animal speaks");
    }
}

public class Dog : Animal
{
    public override void Speak()
    {
        Console.WriteLine("Dog barks");
    }
}

6.2 Using Base Method in Override

You can call the base implementation from the override:

public override void Speak()
{
    base.Speak();
    Console.WriteLine("Dog barks");
}

6.3 Polymorphism and Late Binding

With polymorphism, base class references can point to derived objects:

Animal myAnimal = new Dog();
myAnimal.Speak(); // Output: Dog barks

This decision is made at runtime (late binding), enabling dynamic behavior.

6.4 Sealed Override

You can prevent further overriding using the sealed modifier:

public class Dog : Animal
{
    public sealed override void Speak()
    {
        Console.WriteLine("Dog barks");
    }
}

public class Puppy : Dog
{
    // Compile error if trying to override Speak()
}

7. New Keyword and Method Hiding

Derived classes can hide base class members using the new keyword instead of overriding.

public class BaseClass
{
    public void Show()
    {
        Console.WriteLine("Base Show");
    }
}

public class DerivedClass : BaseClass
{
    public new void Show()
    {
        Console.WriteLine("Derived Show");
    }
}

Unlike overriding, method hiding is resolved at compile time, based on reference type:

BaseClass obj1 = new DerivedClass();
obj1.Show();  // Output: Base Show

DerivedClass obj2 = new DerivedClass();
obj2.Show();  // Output: Derived Show

8. Abstract Classes and Methods

Abstract classes provide a base class with incomplete implementation and must be inherited.

8.1 Declaring Abstract Classes

public abstract class Shape
{
    public abstract double GetArea(); // Abstract method without body
}

8.2 Implementing Abstract Methods

public class Circle : Shape
{
    public double Radius;

    public Circle(double radius)
    {
        Radius = radius;
    }

    public override double GetArea()
    {
        return Math.PI * Radius * Radius;
    }
}

8.3 Cannot Instantiate Abstract Classes

// Shape shape = new Shape(); // Compile error

9. Interfaces and Inheritance

While classes support single inheritance, C# allows a class to implement multiple interfaces, enabling a form of multiple inheritance.

public interface IPlayable
{
    void Play();
}

public interface IRecordable
{
    void Record();
}

public class MediaPlayer : IPlayable, IRecordable
{
    public void Play() { Console.WriteLine("Playing media"); }
    public void Record() { Console.WriteLine("Recording media"); }
}

10. Best Practices for Using Inheritance

  • Favor Composition over Inheritance: Use inheritance only when there is a clear "is-a" relationship.
  • Keep Inheritance Hierarchies Shallow: Deep hierarchies are harder to maintain.
  • Use Virtual and Override Wisely: Avoid unnecessary virtual methods for better performance and maintainability.
  • Be Careful with Method Hiding: It can introduce subtle bugs if misunderstood.
  • Prefer Interfaces for Multiple Inheritance: Use interfaces when you need to implement multiple behaviors.

11. Practical Example: Inheritance in a Banking System

public class Account
{
    public string AccountNumber { get; set; }
    public decimal Balance { get; protected set; }

    public Account(string number, decimal initialBalance)
    {
        AccountNumber = number;
        Balance = initialBalance;
    }

    public virtual void Deposit(decimal amount)
    {
        Balance += amount;
        Console.WriteLine($"Deposited {amount}, new balance: {Balance}");
    }

    public virtual void Withdraw(decimal amount)
    {
        if (amount <= Balance)
        {
            Balance -= amount;
            Console.WriteLine($"Withdrew {amount}, new balance: {Balance}");
        }
        else
        {
            Console.WriteLine("Insufficient funds");
        }
    }
}

public class SavingsAccount : Account
{
    public double InterestRate { get; set; }

    public SavingsAccount(string number, decimal balance, double interestRate)
        : base(number, balance)
    {
        InterestRate = interestRate;
    }

    public void AddInterest()
    {
        decimal interest = Balance * (decimal)InterestRate / 100;
        Deposit(interest);
        Console.WriteLine($"Interest added: {interest}");
    }
}

public class CheckingAccount : Account
{
    public decimal OverdraftLimit { get; set; }

    public CheckingAccount(string number, decimal balance, decimal overdraft)
        : base(number, balance)
    {
        OverdraftLimit = overdraft;
    }

    public override void Withdraw(decimal amount)
    {
        if (amount <= Balance + OverdraftLimit)
        {
            Balance -= amount;
            Console.WriteLine($"Withdrew {amount}, new balance: {Balance}");
        }
        else
        {
            Console.WriteLine("Exceeded overdraft limit");
        }
    }
}

Inheritance is a foundational concept in C# and OOP that facilitates reuse, organization, and polymorphism. It enables a derived class to inherit and modify behavior of a base class, promoting extensible and maintainable code.

Key points:

  • Use inheritance to express "is-a" relationships.
  • Derived classes inherit fields, properties, and methods of base classes.
  • Virtual and override enable polymorphic behavior.
  • Use base keyword to access base class members.
  • Abstract classes define incomplete bases, interfaces enable multiple inheritance.
  • Beware of deep hierarchies and method hiding pitfalls.

Mastering inheritance unlocks powerful design patterns and clean, scalable software architecture in C#.

logo

C#

Beginner 5 Hours

Inheritance in C#

Inheritance is one of the core pillars of Object-Oriented Programming (OOP) in C#. It enables new classes to be based on existing classes, promoting code reuse, extensibility, and a clear hierarchical relationship between types. This detailed guide covers everything you need to know about inheritance in C#, from basic concepts to advanced usage, including examples and best practices.

1. Introduction to Inheritance

Inheritance allows a class (called the derived class or child class) to inherit members (fields, properties, methods, events) from another class (called the base class or parent class). This relationship models an "is-a" association — the derived class is a specialized version of the base class.

1.1 Why Use Inheritance?

  • Code Reuse: Avoid rewriting common functionality by inheriting it from a base class.
  • Extensibility: Extend or modify behavior without changing the original class.
  • Polymorphism: Use a base class reference to refer to derived class objects for flexible code.
  • Logical Hierarchies: Represent real-world relationships naturally.

1.2 Real-World Example

Consider a base class Animal and derived classes like Dog and Cat. Dogs and cats share common animal properties (like breathing and eating) but also have specialized behaviors.

2. Basic Syntax of Inheritance in C#

Inheritance is implemented using the colon (:) syntax after the derived class name.

public class Animal { public void Eat() { Console.WriteLine("Eating..."); } } public class Dog : Animal { public void Bark() { Console.WriteLine("Barking..."); } }

In this example, Dog inherits Eat() method from Animal, and also has its own Bark() method.

2.1 Creating and Using Derived Class Objects

Dog myDog = new Dog(); myDog.Eat(); // Output: Eating... myDog.Bark(); // Output: Barking...

3. Types of Inheritance in C#

C# supports several inheritance patterns:

3.1 Single Inheritance

One derived class inherits from one base class.

class Vehicle { public void Start() => Console.WriteLine("Vehicle started."); } class Car : Vehicle { public void Drive() => Console.WriteLine("Car is driving."); }

3.2 Multilevel Inheritance

A class derives from a derived class.

class Animal { public void Eat() => Console.WriteLine("Eating..."); } class Mammal : Animal { public void Walk() => Console.WriteLine("Walking..."); } class Dog : Mammal { public void Bark() => Console.WriteLine("Barking..."); }

3.3 Hierarchical Inheritance

Multiple classes inherit from a single base class.

class Animal { public void Eat() => Console.WriteLine("Eating..."); } class Dog : Animal { public void Bark() => Console.WriteLine("Barking..."); } class Cat : Animal { public void Meow() => Console.WriteLine("Meowing..."); }

3.4 Multiple Inheritance (via Interfaces)

C# does not support multiple class inheritance but allows multiple interface inheritance.

interface IWalkable { void Walk(); } interface ISwimmable { void Swim(); } class Amphibian : IWalkable, ISwimmable { public void Walk() => Console.WriteLine("Walking..."); public void Swim() => Console.WriteLine("Swimming..."); }

4. Access Modifiers and Inheritance

Access modifiers control visibility of class members in inheritance scenarios.

Modifier Access within Derived Class Access Outside Assembly
publicYesYes
privateNoNo
protectedYesNo
internalYes (if same assembly)No
protected internalYesYes if same assembly

4.1 Protected Members

protected members are accessible only within the class and its derived classes, which is key for inheritance encapsulation.

public class Animal { protected string name; protected void SetName(string n) { name = n; } } public class Dog : Animal { public void Initialize(string dogName) { SetName(dogName); Console.WriteLine($"Dog's name is {name}"); } }

5. Constructors and Inheritance

Derived classes do not inherit constructors but can call base class constructors explicitly using the base keyword.

5.1 Base Constructor Call

public class Person { public string Name; public Person(string name) { Name = name; } } public class Employee : Person { public int EmployeeId; public Employee(string name, int id) : base(name) { EmployeeId = id; } }

5.2 Constructor Execution Order

When creating an object of a derived class:

  • Base class constructor runs first.
  • Then derived class constructor executes.

6. Method Overriding and Polymorphism

Inheritance allows derived classes to modify behavior of base class methods via overriding.

6.1 Virtual Methods

Base class methods declared with

virtual can be overridden.

public class Animal { public virtual void Speak() { Console.WriteLine("Animal speaks"); } } public class Dog : Animal { public override void Speak() { Console.WriteLine("Dog barks"); } }

6.2 Using Base Method in Override

You can call the base implementation from the override:

public override void Speak() { base.Speak(); Console.WriteLine("Dog barks"); }

6.3 Polymorphism and Late Binding

With polymorphism, base class references can point to derived objects:

Animal myAnimal = new Dog(); myAnimal.Speak(); // Output: Dog barks

This decision is made at runtime (late binding), enabling dynamic behavior.

6.4 Sealed Override

You can prevent further overriding using the

sealed modifier:

public class Dog : Animal { public sealed override void Speak() { Console.WriteLine("Dog barks"); } } public class Puppy : Dog { // Compile error if trying to override Speak() }

7. New Keyword and Method Hiding

Derived classes can hide base class members using the new keyword instead of overriding.

public class BaseClass { public void Show() { Console.WriteLine("Base Show"); } } public class DerivedClass : BaseClass { public new void Show() { Console.WriteLine("Derived Show"); } }

Unlike overriding, method hiding is resolved at compile time, based on reference type:

BaseClass obj1 = new DerivedClass(); obj1.Show(); // Output: Base Show DerivedClass obj2 = new DerivedClass(); obj2.Show(); // Output: Derived Show

8. Abstract Classes and Methods

Abstract classes provide a base class with incomplete implementation and must be inherited.

8.1 Declaring Abstract Classes

public abstract class Shape { public abstract double GetArea(); // Abstract method without body }

8.2 Implementing Abstract Methods

public class Circle : Shape { public double Radius; public Circle(double radius) { Radius = radius; } public override double GetArea() { return Math.PI * Radius * Radius; } }

8.3 Cannot Instantiate Abstract Classes

// Shape shape = new Shape(); // Compile error

9. Interfaces and Inheritance

While classes support single inheritance, C# allows a class to implement multiple interfaces, enabling a form of multiple inheritance.

public interface IPlayable { void Play(); } public interface IRecordable { void Record(); } public class MediaPlayer : IPlayable, IRecordable { public void Play() { Console.WriteLine("Playing media"); } public void Record() { Console.WriteLine("Recording media"); } }

10. Best Practices for Using Inheritance

  • Favor Composition over Inheritance: Use inheritance only when there is a clear "is-a" relationship.
  • Keep Inheritance Hierarchies Shallow: Deep hierarchies are harder to maintain.
  • Use Virtual and Override Wisely: Avoid unnecessary virtual methods for better performance and maintainability.
  • Be Careful with Method Hiding: It can introduce subtle bugs if misunderstood.
  • Prefer Interfaces for Multiple Inheritance: Use interfaces when you need to implement multiple behaviors.

11. Practical Example: Inheritance in a Banking System

public class Account { public string AccountNumber { get; set; } public decimal Balance { get; protected set; } public Account(string number, decimal initialBalance) { AccountNumber = number; Balance = initialBalance; } public virtual void Deposit(decimal amount) { Balance += amount; Console.WriteLine($"Deposited {amount}, new balance: {Balance}"); } public virtual void Withdraw(decimal amount) { if (amount <= Balance) { Balance -= amount; Console.WriteLine($"Withdrew {amount}, new balance: {Balance}"); } else { Console.WriteLine("Insufficient funds"); } } } public class SavingsAccount : Account { public double InterestRate { get; set; } public SavingsAccount(string number, decimal balance, double interestRate) : base(number, balance) { InterestRate = interestRate; } public void AddInterest() { decimal interest = Balance * (decimal)InterestRate / 100; Deposit(interest); Console.WriteLine($"Interest added: {interest}"); } } public class CheckingAccount : Account { public decimal OverdraftLimit { get; set; } public CheckingAccount(string number, decimal balance, decimal overdraft) : base(number, balance) { OverdraftLimit = overdraft; } public override void Withdraw(decimal amount) { if (amount <= Balance + OverdraftLimit) { Balance -= amount; Console.WriteLine($"Withdrew {amount}, new balance: {Balance}"); } else { Console.WriteLine("Exceeded overdraft limit"); } } }

Inheritance is a foundational concept in C# and OOP that facilitates reuse, organization, and polymorphism. It enables a derived class to inherit and modify behavior of a base class, promoting extensible and maintainable code.

Key points:

  • Use inheritance to express "is-a" relationships.
  • Derived classes inherit fields, properties, and methods of base classes.
  • Virtual and override enable polymorphic behavior.
  • Use base keyword to access base class members.
  • Abstract classes define incomplete bases, interfaces enable multiple inheritance.
  • Beware of deep hierarchies and method hiding pitfalls.

Mastering inheritance unlocks powerful design patterns and clean, scalable software architecture in C#.

Related Tutorials

Frequently Asked Questions for C#

C# is much easier to learn than C++. C# is a simpler, high-level-of-abstraction language, while C++ is a low-level language with a higher learning curve.

C# outshines Python when it comes to runtime performance. As a compiled language, C# code is converted to machine code, which can be executed more efficiently by the processor. This results in faster execution times and better performance, especially in resource-intensive tasks.

Python and JavaScript programmers also earn high salaries, ranking #3 and #4 in compensation. 
C# is the highest-paid programming language but has less demand than Python, JavaScript, and Java.

No. Microsoft has invested substantially in ensuring that C# is the dominant language today, spending two billion dollars on marketing and attempting to convince developers to embrace this new platform, which is also based on the.NET foundation.

C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.


You can’t be able to become Master of C# in 3 months since it has many concepts to learn and implement. NOTE: no one can become master in particular programming language. Everyday they introducing new concepts we need to get practice on it which practically somewhat tough.

C-Sharp is one of the most widely used languages for creating system backend.It's because of its incredible features, such as Windows server automation. Apart from that, it's fantastic because it runs codes quite quickly. It can also be used to create CLI applications and game creation.

Easy to learn and use: C# is simpler than Java due to its use of fewer keywords and usually shorter lines of code. Hence, it is easier to learn to code in C# compared to Java. Flexible Data Types: C# provides more flexibility in defining data types than Java.

Four steps of code compilation in C# include : 
  • Source code compilation in managed code.
  • Newly created code is clubbed with assembly code.
  • The Common Language Runtime (CLR) is loaded.
  • Assembly execution is done through CLR.

The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.


The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.


Among other languages, C# is gaining huge popularity for developing web-based applications. Its core concepts help build an interactive environment and provide functionalities that the dynamic web platform requires. Most aspiring full-stack developers choose this versatile language.

The C# programming language was designed by Anders Hejlsberg from Microsoft in 2000 and was later approved as an international standard by Ecma (ECMA-334) in 2002 and ISO/IEC (ISO/IEC 23270 and 20619) in 2003. Microsoft introduced C# along with .NET Framework and Visual Studio, both of which were closed-source. 

C# outshines Python when it comes to runtime performance. As a compiled language, C# code is converted to machine code, which can be executed more efficiently by the processor. This results in faster execution times and better performance, especially in resource-intensive tasks.

Yes, C# is used by many large organizations, start-ups and beginners alike. It takes some of the useful features of C and adds syntax to save time and effort. Although C# is based on C, you can learn it without any knowledge of C β€” in fact, this course is perfect for those with no coding experience at all!

C# is a very mature language that evolved significantly over the years.
The C# language is one of the top 5 most popular programming languages and .NET is the most loved software development framework in the world.
TIOBE Index predicts C# as 2023 'Language of the Year' close to overtake Java in popularity.

Generally, the C# language is not limited to the Windows operating system. In a sense, however, it is limited to Microsoft software. C# language "belongs" to Microsoft, it is developed by Microsoft and it is Microsoft that provides the runtime environment required for the operation of programs written in C#.

C# (pronounced "C sharp") is called so because the "#" symbol is often referred to as "sharp." The name was chosen by Microsoft when they developed the language. It's a play on words related to musical notation where "C#" represents the musical note C sharp.

Dennis MacAlistair Ritchie (September 9, 1941 – c. October 12, 2011) was an American computer scientist. He created the C programming language and, with long-time colleague Ken Thompson, the Unix operating system and B language.

C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.


line

Copyrights © 2024 letsupdateskills All rights reserved