C# Interface

C# Interface

An interface in C# is a contract that defines methods, properties, events, or indexers without any implementation.
A class that implements an interface must provide the implementation for all its members.

Interfaces are a key part of abstraction and polymorphism.


🔹 Syntax



 


🔹 Implementing an Interface



 


🔹 Multiple Interface Implementation

A class can implement multiple interfaces (C# supports multiple inheritance via interfaces).


 


🔹 Interface Properties


 


🔹 Interface Methods Default Implementation (C# 8.0+)

C# 8.0 allows default implementation in interfaces:



 


🔹 Interface vs Abstract Class

Feature Interface Abstract Class
Methods Implementation No (except default in C# 8+) Yes (can have concrete methods)
Fields Not allowed Allowed
Inheritance Multiple interfaces allowed Single inheritance only
Constructor Not allowed Allowed
Access Modifiers Public only (by default) Any (public, protected, private)

🔹 Advantages of Interfaces

✔ Enforce a contract for classes
✔ Supports multiple inheritance
✔ Promotes loose coupling and flexibility
✔ Helps implement polymorphism


🔹 Common Mistakes

❌ Forgetting to implement all interface members
❌ Trying to instantiate an interface
❌ Mixing interfaces and abstract class rules


🔹 Summary

  • Interface = contract

  • Classes must implement all members

  • Supports multiple inheritance

  • Essential for abstraction and polymorphism

You may also like...