1.8 — Interfaces¶
← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.7 Inheritance · Next: 1.9 Polymorphism
Markers: 🔥 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
- An interface is a contract. It lists what a type can do, without saying how.
- A class can implement many interfaces but inherit from only one class. That is often the deciding factor.
- Interfaces are what make dependency injection and unit testing possible — you depend on the contract, and swap the real thing for a fake one in tests.
The concept¶
An interface is a list of promises. It says "any type claiming to be this must provide these members" — but it does not say how.
A good real-world comparison is a wall socket. The socket is the interface. It promises a certain shape and a certain voltage. A lamp, a laptop charger and a kettle all plug into the same socket, and the socket does not know or care what they do with the electricity. You can unplug one and plug in another, and the wall does not change.
That is exactly why interfaces matter in real applications. Your code plugs into
IEmailSender. In production you plug in the real one that talks to SendGrid. In tests you
plug in a fake one that just records what was sent. Your code never changes.
How it works¶
Declaring and implementing¶
public interface IEmailSender
{
Task SendAsync(string to, string subject, string body);
}
public class SendGridEmailSender : IEmailSender
{
public Task SendAsync(string to, string subject, string body)
{
// real implementation
}
}
Notice the interface has no body for the method — just the signature and a semicolon.
Interface members are automatically public; you cannot and should not write public in
front of them.
One class, many interfaces¶
This is the key structural difference from inheritance:
public class FileLogger : ILogger, IDisposable, IAsyncDisposable
{
// must implement all members of all three
}
A class can only have one base class, but it can promise as many contracts as it likes. When you need a type to fit into several different systems, interfaces are the only option.
Explicit implementation¶
Sometimes two interfaces declare a member with the same name, or you want a member available only when the object is used through a specific interface. You can implement it explicitly by prefixing the interface name:
public interface IFileReader { string Read(); }
public interface IDatabaseReader { string Read(); }
public class DataSource : IFileReader, IDatabaseReader
{
// Two methods with the same name — distinguished by which interface
string IFileReader.Read() => "from file";
string IDatabaseReader.Read() => "from database";
}
Now watch how you have to call them:
var ds = new DataSource();
ds.Read();
// ERROR — DataSource itself has no public Read method.
// Explicitly implemented members are hidden from the class's own surface.
((IFileReader)ds).Read(); // "from file"
((IDatabaseReader)ds).Read(); // "from database"
IFileReader reader = ds;
reader.Read(); // "from file" — cleaner way to write it
Explicit implementation is also used to hide a member you must implement but do not want
people calling casually — IDisposable.Dispose on a type where disposal should happen a
different way, for example.
Default interface methods (C# 8+)¶
Since C# 8, an interface can provide a body for a method:
public interface ILogger
{
void Log(string message);
// A default. Implementers get this free unless they replace it.
void LogError(Exception ex) => Log($"ERROR: {ex.Message}");
}
This was added mainly so library authors can add a method to an existing interface without breaking everyone who already implements it. Before C# 8, adding a member to a published interface broke every implementer immediately.
It is not meant as a replacement for abstract classes. Interfaces still cannot hold state (no fields), so anything needing shared data still wants a class.
One thing to be careful about: default methods are only visible through the interface, not through the class:
public class ConsoleLogger : ILogger
{
public void Log(string m) => Console.WriteLine(m);
// LogError not implemented — we use the default
}
var logger = new ConsoleLogger();
logger.LogError(ex); // ERROR — not on the class
ILogger asInterface = logger;
asInterface.LogError(ex); // works
Interface vs abstract class¶
| Interface | Abstract class | |
|---|---|---|
| How many can a class have? | Many | One |
| Can hold fields / state? | No | Yes |
| Can have constructors? | No | Yes |
| Can have implemented methods? | Yes, since C# 8 (defaults) | Yes, always |
| Access modifiers on members? | Always public | Any |
| Relationship it expresses | "can do this" | "is a kind of this" |
The practical rule: define the contract as an interface so consumers depend on that. Add an abstract base class only if there is genuinely shared code. That way the base class stays an implementation detail rather than part of your public design.
Code¶
Here is why interfaces matter in ASP.NET Core specifically.
// The contract
public interface IOrderRepository
{
Task<Order?> GetAsync(Guid id, CancellationToken ct);
Task SaveAsync(Order order, CancellationToken ct);
}
// Your business logic depends on the CONTRACT, never on the real database class
public class OrderService(IOrderRepository repo, IEmailSender email)
{
public async Task CompleteAsync(Guid id, CancellationToken ct)
{
var order = await repo.GetAsync(id, ct)
?? throw new NotFoundException(id);
order.Complete();
await repo.SaveAsync(order, ct);
await email.SendAsync(order.CustomerEmail, "Order complete", "Thanks!");
}
}
In production you register the real implementations:
builder.Services.AddScoped<IOrderRepository, SqlOrderRepository>();
builder.Services.AddScoped<IEmailSender, SendGridEmailSender>();
In a unit test you pass in fakes instead:
[Fact]
public async Task CompleteAsync_SendsConfirmationEmail()
{
var repo = Substitute.For<IOrderRepository>();
var email = Substitute.For<IEmailSender>();
repo.GetAsync(id, default).Returns(new Order(id));
var service = new OrderService(repo, email);
await service.CompleteAsync(id, default);
await email.Received(1).SendAsync(Arg.Any<string>(), "Order complete", Arg.Any<string>());
}
This test touches no database and sends no email. It runs in milliseconds. That is only
possible because OrderService asked for interfaces rather than concrete classes. This is
the single most practical reason interviewers care about interfaces.
Interview questions¶
Q: What is an interface and why would you use one?
An interface is a contract that lists what members a type must have, without saying how they work. You use it so that code can depend on what something does rather than how it does it. That gives you two big wins. You can swap implementations without changing the consuming code — the same service can work against SQL Server in production and an in-memory fake in tests. And it lets a class satisfy several contracts at once, which you cannot do with inheritance because C# only allows one base class.
Q: Interface or abstract class — how do you choose?
I ask whether there is shared implementation. If the types genuinely share code and state, and they form a real "is-a" family, an abstract class is right — it can hold fields, have a constructor, and provide finished methods. If I am describing a capability that unrelated types might have, or if the type already needs a different base class, it has to be an interface. In practice I lean towards an interface for the public contract and only add an abstract base class underneath when there is real duplication to remove.
Q: What are default interface methods and why were they added?
Since C# 8, an interface member can have a body, which implementing types inherit unless they override it. The main reason they were added was versioning — before this, adding a method to a published interface broke every single class implementing it. Now a library can add a method with a default body and existing implementers keep compiling. They are not a replacement for abstract classes, because interfaces still cannot hold state.
Q: What is explicit interface implementation?
It is when you implement a member by writing the interface name in front of it, like
string IFileReader.Read(). The member then only exists when the object is accessed
through that interface — it is not part of the class's own public surface. You need it when
two interfaces declare members with the same signature and you want them to behave
differently, or when you have to implement something but do not want to encourage people
to call it directly on the class.
Traps ⚠️¶
- Explicitly implemented members are invisible on the class. You must cast to the interface, or assign to an interface-typed variable, to call them.
- Default interface methods are also only visible through the interface, not through the class that implements it. This surprises people.
- Interfaces cannot hold state. No fields. If your "interface" needs data, it wants to be an abstract class.
- An interface with one implementation and no test double is often unnecessary. Do not create an interface for every class out of habit — that is ceremony without benefit. Add it when you actually need to substitute, mock, or support multiple implementations.
- Adding a member to a published interface is a breaking change unless you give it a default body.
- Interface members are always public. Writing
publicin front is a compile error, and you cannot make oneprivateorprotected.
Related¶
- 1.7 Inheritance — the alternative, and when it fits better
- 1.9 Polymorphism — interfaces are one way to achieve it
- 1.10 Generics — generic interfaces and variance
- 6.1 Dependency injection — why this all matters in ASP.NET Core
- 20.4 Mocking — substituting interfaces in tests
- 22.1 SOLID — interface segregation and dependency inversion