ποΈ C# Interfaces β Define Contracts for Flexible and Scalable Code
π§² Introduction β Why Use Interfaces in C#?
In large-scale C# applications, you often want different classes to follow a common structure or behavior, even if they arenβt related by inheritance. Interfaces make this possible. They act as contracts, ensuring that any class implementing the interface follows its rulesβallowing you to build loosely coupled, extensible systems.
π― In this guide, youβll learn:
- What interfaces are and how to define them
- How to implement interfaces in classes
- Interface inheritance and default methods (C# 8+)
- Real-world examples and use cases
- Differences from abstract classes
π Core Concept β What Is an Interface?
An interface in C# is a contract that defines method signatures, properties, events, or indexersβwithout providing implementation. Any class or struct that implements the interface must provide the actual functionality.
π£ Syntax:
interface IShape
{
void Draw();
double Area { get; }
}
π Naming Convention: Prefix with I
(e.g., IShape
, IAnimal
, IService
)
π§± Implementing an Interface
class Circle : IShape
{
public double Radius { get; set; }
public void Draw()
{
Console.WriteLine("Drawing Circle");
}
public double Area => Math.PI * Radius * Radius;
}
π Circle
provides the actual implementation of Draw()
and Area
.
π Using Interface References
IShape shape = new Circle { Radius = 5 };
shape.Draw();
Console.WriteLine($"Area: {shape.Area}");
π You can reference any class via its interfaceβenabling polymorphism.
π§© Multiple Interface Implementation
interface IReadable { void Read(); }
interface IWritable { void Write(); }
class Document : IReadable, IWritable
{
public void Read() => Console.WriteLine("Reading Document");
public void Write() => Console.WriteLine("Writing Document");
}
π Use Case: Combine multiple behaviors without class inheritance.
π§ Interface Inheritance (Extending Interfaces)
interface IEntity
{
int Id { get; set; }
}
interface IUser : IEntity
{
string Name { get; set; }
}
π Use Case: Build layered and composable contracts.
βοΈ Default Interface Methods (C# 8+)
interface ILogger
{
void Log(string message) => Console.WriteLine(message);
}
π Use Case: Provide default behavior while preserving backward compatibility.
π Interface vs Abstract Class Comparison
Feature | Interface | Abstract Class |
---|---|---|
Inheritance Type | Multiple | Single |
Implementation | No (until C# 8 default methods) | Yes |
Fields Allowed | β No | β Yes |
Use Case | Contract for unrelated classes | Shared base for related classes |
π‘ Best Practices & Tips
π‘ Tip: Favor interfaces for flexibility and loose coupling.
β οΈ Pitfall: Donβt include implementation logic in interfaces (unless using C# 8+ default methods cautiously).
π Best Practice: Use interfaces with dependency injection and test mocking frameworks.
π οΈ Real-World Use Cases
- π³ Payment gateway integrations (
IPaymentProvider
) - π¦ Repository pattern (
IRepository<T>
) - πΌοΈ UI component contracts (
IComponent
) - π§ͺ Unit testing mocks/stubs
- π Plugin architecture (
IPlugin
,IModule
)
π Summary β Recap & Next Steps
π§΅ Key Takeaways:
- Interfaces define what a class must do, not how.
- A class can implement multiple interfaces, supporting better abstraction.
- Interfaces are critical for polymorphism, dependency injection, and clean architecture.
βοΈ Real-world relevance: C# interfaces power SOLID design, APIs, testability, and framework extensibility.
β FAQ Section
β Can I create a method body inside an interface?
β
Yes, starting from C# 8.0 using default interface implementations.
β What happens if a class doesn’t implement all interface members?
β
β It wonβt compile unless the class is marked abstract
.
β Can interfaces have fields or constructors?
β
β No. Interfaces cannot contain fields or constructors.
β Can I implement multiple interfaces in a class?
β
Yes! C# fully supports multiple interface implementation.
β Should I use interfaces or abstract classes?
β
Use interfaces for contracts across unrelated classes.
β
Use abstract classes for partial implementation across related classes.
Share Now :