Lesson 16 of 24
In progress
Interfaces and composition
Define a contract, implement it across unrelated types, and use default interface methods without turning the interface into a base class.
An interface names what a type can do. Since C# classes inherit from only one base class, interfaces are how a type takes on several roles — and how code depends on behaviour rather than on a concrete class.
What you will learn
- Declare and implement an interface.
- Use default interface methods and explicit implementation.
- Design small interfaces that compose.
The contract
public interface INotifier
{
void Send(string to, string message);
}
public class EmailNotifier : INotifier
{
public void Send(string to, string message) =>
Console.WriteLine($"email to {to}: {message}");
}
public class SmsNotifier : INotifier
{
public void Send(string to, string message) =>
Console.WriteLine($"sms to {to}: {message}");
}
Implementing members must be public, because the interface is public. The I prefix is the .NET convention for interfaces, unlike Java; follow it in .NET code even though it duplicates the type-kind information.
Using the interface as the type
static void NotifyAll(IEnumerable<INotifier> notifiers, string to, string message)
{
foreach (var notifier in notifiers)
{
notifier.Send(to, message);
}
}
The method depends only on the contract. Adding a push notifier means implementing INotifier and passing it in, with no change here.
IEnumerable<T> rather than List<T> in the parameter is the same idea one level down: accept the least specific type you need, so arrays and query results work too.
Default implementations
public interface INotifier
{
void Send(string to, string message);
void SendAll(IEnumerable<string> recipients, string message)
{
foreach (var recipient in recipients)
{
Send(recipient, message);
}
}
}
A default method is inherited by every implementer that does not override it. It lets an interface grow without breaking implementations, which is why .NET added the feature.
The cost is the same as in Java: an interface with many default methods carrying behaviour becomes a base class without fields. Keep defaults small and derived from the abstract members.
Explicit implementation
public class QuietNotifier : INotifier
{
void INotifier.Send(string to, string message) { /* does nothing */ }
}
An explicit implementation is callable only through the interface:
INotifier notifier = new QuietNotifier();
notifier.Send("a", "b"); // compiles
// new QuietNotifier().Send(...) // does not
That is useful when two interfaces declare the same member with different meanings, or when a member should not clutter the class’s public surface.
Small interfaces
public interface IReader { string Read(); }
public interface IWriter { void Write(string text); }
public interface IReadWriter : IReader, IWriter { }
Two focused interfaces can be combined, and a class that only reads implements IReader. A test double does the same without pretending to write.
Splitting a five-member interface is usually an improvement, because callers depend only on what they use. Splitting every interface into one member each is not; the guideline is whether different callers use different subsets.
Interfaces for testability
public interface IClock
{
DateTimeOffset Now { get; }
}
public class SystemClock : IClock
{
public DateTimeOffset Now => DateTimeOffset.UtcNow;
}
public class FixedClock : IClock
{
public FixedClock(string iso) => Now = DateTimeOffset.Parse(iso);
public DateTimeOffset Now { get; }
}
Code that needs the current time takes an IClock instead of calling DateTimeOffset.UtcNow. A test passes a fixed clock, so an expiry rule can be tested without waiting.
That is the main practical value of interfaces in application code: they name a dependency that can be substituted.
Interfaces versus abstract classes
| Need | Choose |
|---|---|
| A contract several unrelated types satisfy | Interface |
| Shared state or a partial implementation | Abstract class |
| Both | Abstract class implementing the interface |
An interface cannot hold instance state, so it cannot enforce an invariant across implementations. An abstract class can, at the cost of single inheritance.
Designing with interfaces
- Name the capability, not the implementation:
IPriced,IExportable,IClock. - Keep them small and cohesive; one reason to change.
- Accept interfaces in parameters and return concrete types from factories.
- Do not create an interface for a type with one implementation and no test double; it adds indirection for nothing.
Return concrete types where the caller needs specific behaviour, and interfaces where the caller only needs the contract. A method that returns IEnumerable<T> is easier to consume than one that returns an array, because the caller can decide whether to loop, count or materialise.
The last point is worth repeating, because "extract an interface" is applied as a reflex in some codebases. An interface earns its place when there are two implementations or a boundary that a test needs to cross.
Creating an interface with a single method for every class, which doubles the type count and hides the dependency graph. Add the interface when substitution is real.
Define IPriced with a Price property, implement it for a Book and a Course, and write a method that totals a sequence of them.
Show solution
public interface IPriced { decimal Price { get; } } public record Book(string Title, decimal Price) : IPriced; public record Course(string Name, decimal Price) : IPriced; static decimal Total(IEnumerable<IPriced> items) => items.Sum(i => i.Price); Console.WriteLine(Total(new IPriced[] { new Book("Small Systems", 450m), new Course("C#", 1299m) })); Records can implement interfaces, so both types satisfy IPriced without sharing a base class. Total depends only on the contract, and a third type would need no change to it.
Recap
- An interface is a public contract; implementations are interchangeable wherever it is expected.
- Default methods let an interface grow; explicit implementation hides a member from the class surface.
- Add an interface when there is a real second implementation or a test boundary.
Module 4 covers collections, LINQ, exceptions, files and async.
Should every interface start with I?
Can an interface have properties?
Progress is saved in this browser only. No account, no email.