0
0
C Sharp (C#)programming~3 mins

Why Default interface methods in C Sharp (C#)? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could add new features to your code without breaking everything that already works?

The Scenario

Imagine you have several classes that share some common behavior defined by an interface. You want to add a new method to this interface, but now every class that implements it must update their code to include this new method.

The Problem

This manual update is slow and error-prone because you must find and change every class that implements the interface. Missing one class causes bugs. It's like having to rewrite parts of many recipes just because you want to add a new ingredient.

The Solution

Default interface methods let you add new methods with a default implementation directly in the interface. This means existing classes don't have to change unless they want to customize the new method. It's like adding a new optional step to a recipe that cooks can follow if they want, without breaking old recipes.

Before vs After
Before
interface IShape { void Draw(); }
// Adding new method requires all classes to implement it
class Circle : IShape { public void Draw() { } /* must add new method here */ }
After
interface IShape {
  void Draw();
  void Resize() { /* default resize code */ }
}
// Circle class does not need to change unless it wants to override Resize
What It Enables

It enables evolving interfaces without breaking existing code, making software easier to maintain and extend.

Real Life Example

Think of a smartphone app interface that adds a new feature. Default interface methods let developers add this feature without forcing all existing apps to update immediately.

Key Takeaways

Manually updating all classes for interface changes is tedious and risky.

Default interface methods provide a safe default implementation inside interfaces.

This allows interfaces to grow without breaking existing code.