C# Multiple Interfaces

C# Multiple Interfaces

In C#, a class can implement multiple interfaces, which allows it to inherit behavior from more than one contract.
This is C#’s way to achieve multiple inheritance, because a class cannot inherit from multiple classes directly.


🔹 Syntax

class ClassName : Interface1, Interface2, Interface3
{
// Implement all interface members
}

🔹 Example: Multiple Interfaces

interface IFlyable
{
void Fly();
}

interface ISwimmable
{
void Swim();
}

class Duck : IFlyable, ISwimmable
{
public void Fly()
{
Console.WriteLine("Duck is flying");
}

public void Swim()
{
Console.WriteLine("Duck is swimming");
}
}

Duck d = new Duck();
d.Fly(); // Duck is flying
d.Swim(); // Duck is swimming

🔹 Implementing Multiple Interfaces with Overlapping Methods

If interfaces have the same method signature, the class can implement them explicitly.

interface IA
{
void Show();
}

interface IB
{
void Show();
}

class Demo : IA, IB
{
void IA.Show()
{
Console.WriteLine("Interface A Show");
}

void IB.Show()
{
Console.WriteLine("Interface B Show");
}
}

Demo obj = new Demo();
((IA)obj).Show(); // Interface A Show
((IB)obj).Show(); // Interface B Show

🔹 Interface Properties

interface IPerson
{
string Name { get; set; }
}

interface IEmployee
{
int EmployeeId { get; set; }
}

class Staff : IPerson, IEmployee
{
public string Name { get; set; }
public int EmployeeId { get; set; }
}


🔹 Advantages of Multiple Interfaces

✔ Achieve multiple inheritance safely
✔ Enforce multiple contracts
✔ Provides flexibility in design
✔ Supports polymorphism


🔹 Common Mistakes

❌ Not implementing all members of all interfaces
❌ Forgetting explicit implementation when methods overlap
❌ Trying to inherit multiple classes instead of interfaces


🔹 Summary

  • C# allows a class to implement multiple interfaces

  • Each interface member must be implemented

  • Supports flexible, modular, and reusable code

  • Useful for polymorphism and abstraction

You may also like...