Saturday, 15 November 2025

Multiple Inheritance in C#

Multiple Inheritance in C#

Can a Class Inherit from Multiple Classes in C#?

No. In C#, a class cannot inherit from more than one class directly. This restriction is in place to avoid ambiguity problems such as the diamond problem that can occur in multiple inheritance.

Example (Not Allowed)

class A { }
class B { }

class C : A, B { }  // ❌ This is NOT allowed in C#
    

How C# Handles Multiple Inheritance

  • C# supports multiple inheritance via interfaces. A class can implement multiple interfaces.
  • This avoids ambiguity because interfaces only define method signatures, and the implementing class provides the actual implementation.

Example Using Interfaces

interface IA {
    void MethodA();
}

interface IB {
    void MethodB();
}

class C : IA, IB {
    public void MethodA() {
        Console.WriteLine("MethodA implementation");
    }

    public void MethodB() {
        Console.WriteLine("MethodB implementation");
    }
}
    

Summary: C# does not allow multiple class inheritance, but multiple interfaces can be implemented to achieve similar behavior.

No comments:

Post a Comment