Multiple Interfaces
A class can sign up for many interfaces at once, like a student who is in the choir, the chess club, and the soccer team. It just needs to keep the promises of each.
In this page:
Syntax
class ClassName : IFirst, ISecond
{
// implement all members of both interfaces
}
Multiple Interfaces
Unlike class inheritance, a class can implement any number of interfaces at once, separated by commas. This lets a single type satisfy several unrelated contracts simultaneously. It's C#'s way of achieving multiple-inheritance-like behavior safely.
Note:
Use several small, focused interfaces rather than one large one — it's easier for classes to mix and match.
Example: Multiple Interfaces
using System;
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");
}
class Program
{
static void Main(string[] args)
{
Duck d = new Duck();
d.Fly();
d.Swim();
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Two interfaces with the same method name conflicting and not using explicit implementation.
- Forgetting to implement members from one of the interfaces.
- Assuming a class can inherit from more than one class the way it can implement many interfaces.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: