8️⃣ C# Object-Oriented Programming (OOP)
Estimated reading: 3 minutes 27 views

πŸ—οΈ 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

FeatureInterfaceAbstract Class
Inheritance TypeMultipleSingle
ImplementationNo (until C# 8 default methods)Yes
Fields Allowed❌ Noβœ… Yes
Use CaseContract for unrelated classesShared 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ—οΈ C# Interfaces

Or Copy Link

CONTENTS
Scroll to Top