Interfaces: The Service Contract

Interfaces: The Service Contract in C#: A contract with a supplier lists obligations, not methods.

The Analogy: The Supplier Contract

A contract with a supplier lists obligations, not methods. "Deliver 200 loaves by 6am daily, invoice monthly." It says nothing about ovens, vans, staff rotas or whether the baking happens in one kitchen or five. Any bakery that can meet those terms can be swapped in, and your café's morning routine does not change a line.

An interface is that contract. interface IPaymentGateway says: whoever you are, you can tell me your name and you can try to charge an amount. Stripe can sign it. PayPal can sign it. A fake that always succeeds, used by your tests at eight in the morning with no network connection, can sign it too — and the checkout code cannot tell the difference, which is precisely why it is worth writing.

The contrast with an abstract class is worth holding onto from the start. An abstract class is a half-built machine you extend; an interface is a promise you sign. You may extend one machine and sign any number of promises, which is why unrelated types — a FileStream, a DbConnection and a SemaphoreSlim — can all be IDisposable without sharing an ancestor.


Syntax or Core Structure

using System;
using System.Collections.Generic;

interface IShape
{
    double Area { get; }                              // properties: get-only here
    string Name { get; }
    string Describe() => $"{Name}: {Area:F2}";         // C# 8: a default implementation
}

interface IScalable
{
    void ScaleBy(double factor);
}

class Circle : IShape, IScalable                      // two contracts, one class
{
    private double radius;
    public Circle(double radius) => this.radius = radius;

    public string Name => "circle";
    public double Area => Math.PI * radius * radius;
    public void ScaleBy(double factor) => radius *= factor;
}

class Square : IShape                                 // no ScaleBy: squares are fixed here
{
    public Square(double side) => Side = side;

    public double Side { get; }
    public string Name => "square";
    public double Area => Side * Side;
    public string Describe() => $"square of side {Side:F1}";   // replaces the default
}

class Program
{
    static double Total(IEnumerable<IShape> shapes)    // accepts a List, an array, anything
    {
        double sum = 0;
        foreach (IShape s in shapes) sum += s.Area;
        return sum;
    }

    static void Main()
    {
        var shapes = new List<IShape> { new Circle(1.0), new Square(3.0), new Circle(0.5) };

        foreach (IShape s in shapes)
            Console.WriteLine(s.Describe());

        shapes.Sort((a, b) => a.Area.CompareTo(b.Area));
        Console.WriteLine($"smallest {shapes[0].Name}, largest {shapes[^1].Name}");

        foreach (IShape s in shapes)
            if (s is IScalable scalable) scalable.ScaleBy(2.0);   // only those that signed

        Console.WriteLine($"after scaling: {string.Join(", ", shapes.ConvertAll(s => s.Describe()))}");
        Console.WriteLine($"total area {Total(shapes):F2}");
    }
}

Output:

circle: 3.14
square of side 3.0
circle: 0.79
smallest circle, largest square
after scaling: circle: 3.14, circle: 12.57, square of side 3.0
total area 24.71

Circle never declares Describe and still has one, courtesy of the interface's default implementation. Square declares its own and that wins. And the is IScalable test is how you ask "did this one sign the other contract?" — the squares are skipped without a single type name appearing in the loop.


Technical Depth: What the Contract Really Means

Interface or abstract class?

The abstraction lesson promised the details here. This is the table:

QuestionAbstract classInterface
How many can a type take?OneAny number
Can it hold fields / state?YesNo (only static fields)
Can it have a constructor?Yes, run by base(...)No
Can members be private, protected?Yesprivate only with a body; no protected state
Default behaviour for members?Normal method bodiesOnly via default implementations (C# 8+)
Are implementers a "family"?Yes — Pallet is a ParcelNot necessarily — a socket and a bitmap can both be IDisposable
Adding a member laterSafe if non-abstractBreaks every implementer unless it has a default body

Rule of thumb: shared state and shared code → abstract class. Shared capability across unrelated types → interface. They combine happily; List<T> inherits from nothing interesting and implements six interfaces.

Implicit versus explicit implementation

Most implementations are implicit: a public member whose signature matches. It is then callable on the class and through the interface. An explicit implementation names the interface and is callable only through it:

interface IFile   { void Close(); }
interface ISocket { void Close(); }

class Bridge : IFile, ISocket
{
    void IFile.Close()   => Console.WriteLine("file closed");     // no access modifier allowed
    void ISocket.Close() => Console.WriteLine("socket closed");
}

var b = new Bridge();
// b.Close();                        // CS1061: no such member on Bridge
((IFile)b).Close();                  // file closed
((ISocket)b).Close();                // socket closed

Two reasons to reach for it: a genuine name collision like this one, and hiding a member you must supply but do not want on the class's public face (implementing IDisposable.Dispose explicitly and exposing a friendlier Close() is a classic).

Default implementations, and their sharp edge

A default body (C# 8) lets you add a member to a shipped interface without breaking implementers. But it is not inherited into the class — it lives on the interface:

IShape shape = new Circle(1.0);
Console.WriteLine(shape.Describe());        // fine: 3.14 via the default
// new Circle(1.0).Describe();              // CS1061: Circle has no Describe

Treat defaults as a versioning tool, not a substitute for a base class.

The interfaces you should recognise

InterfaceYou implement it to…Unlocks
IComparable<T>define a natural orderArray.Sort, List<T>.Sort, OrderBy
IEquatable<T>define value equality without boxingContains, Distinct, dictionary keys
IEnumerable<T>be iterableforeach, all of LINQ
IDisposableown an unmanaged or scarce resourceusing blocks
IFormattablehonour format strings$"{x:F2}" on your own type
IReadOnlyList<T>expose a list without letting callers mutate itsafe public surfaces

Implementing IComparable<T> is the cheapest win of the six:

class Version : IComparable<Version>
{
    public int Major, Minor;
    public int CompareTo(Version? other) =>
        other is null ? 1
        : Major != other.Major ? Major.CompareTo(other.Major)
        : Minor.CompareTo(other.Minor);
}

Structs, boxing and static abstract members

A struct may implement an interface, but reaching it through the interface boxes the value onto the heap — the usual reason a hot loop over IComparable is slower than the same loop over a generic T where T : IComparable<T>, which the JIT specialises with no boxing at all.

C# 11 added static abstract members, letting an interface demand statics — which is how INumber<T> makes + writable in generic code:

interface IZero<T> { static abstract T Zero { get; } }

static T SumAll<T>(IEnumerable<T> xs) where T : IZero<T>, IAdditionOperators<T, T, T>
{
    T total = T.Zero;                       // calling a static through the type parameter
    foreach (T x in xs) total = total + x;
    return total;
}

Variance

IEnumerable<out T> is covariant, so an IEnumerable<string> is usable as an IEnumerable<object>. IComparer<in T> is contravariant: a IComparer<object> will happily compare strings. This is why Total(IEnumerable<IShape>) above accepts a List<Circle> too — and why arrays' unsound covariance (last lesson) is not needed here.

Keep contracts small

IScalable is separate from IShape on purpose. Had ScaleBy been bolted onto IShape, every square would need a method it cannot honour — the usual sign of a contract asking for too much. Small interfaces compose; fat ones force implementers to throw NotSupportedException, which is a runtime apology for a compile-time mistake.


Real World Example: A Checkout You Can Test at 3am

The single most valuable thing interfaces buy you is a class you can test without a network, a database or a clock. CheckoutService below depends on three contracts and knows nothing about who signed them.

using System;
using System.Collections.Generic;

interface IClock { DateTime Now { get; } }

interface IAuditLog
{
    void Record(string entry);
    IReadOnlyList<string> Entries { get; }
}

interface IPaymentGateway
{
    string Name { get; }
    bool TryCharge(decimal amount, out string reference);
}

class CheckoutService
{
    private readonly IPaymentGateway gateway;
    private readonly IAuditLog log;
    private readonly IClock clock;

    public CheckoutService(IPaymentGateway gateway, IAuditLog log, IClock clock)
    {
        this.gateway = gateway;      // injected, not constructed here
        this.log = log;
        this.clock = clock;
    }

    public bool Pay(decimal amount)
    {
        if (amount <= 0m)
        {
            log.Record($"{clock.Now:HH:mm} rejected {amount:F2}: not positive");
            return false;
        }

        if (!gateway.TryCharge(amount, out string reference))
        {
            log.Record($"{clock.Now:HH:mm} declined {amount:F2} via {gateway.Name}");
            return false;
        }

        log.Record($"{clock.Now:HH:mm} charged {amount:F2} via {gateway.Name} ref {reference}");
        return true;
    }
}

// --- three stand-ins: no network, no database, no real clock ---

class FixedClock : IClock
{
    public FixedClock(DateTime now) => Now = now;
    public DateTime Now { get; }
}

class MemoryLog : IAuditLog
{
    private readonly List<string> entries = new();
    public void Record(string entry) => entries.Add(entry);
    public IReadOnlyList<string> Entries => entries;      // callers can read, not append
}

class FakeGateway : IPaymentGateway
{
    private readonly decimal limit;
    private int counter;

    public FakeGateway(string name, decimal limit) { Name = name; this.limit = limit; }

    public string Name { get; }

    public bool TryCharge(decimal amount, out string reference)
    {
        if (amount > limit) { reference = ""; return false; }
        reference = $"REF-{++counter:D3}";
        return true;
    }
}

class Program
{
    static void Main()
    {
        var log = new MemoryLog();
        var clock = new FixedClock(new DateTime(2026, 5, 4, 9, 30, 0));
        var service = new CheckoutService(new FakeGateway("stripe-sim", 100m), log, clock);

        Console.WriteLine($"pay 42.00  -> {service.Pay(42.00m)}");
        Console.WriteLine($"pay 250.00 -> {service.Pay(250.00m)}");
        Console.WriteLine($"pay -5.00  -> {service.Pay(-5.00m)}");
        Console.WriteLine($"pay 12.50  -> {service.Pay(12.50m)}");

        Console.WriteLine($"audit trail ({log.Entries.Count} entries):");
        foreach (string entry in log.Entries) Console.WriteLine($"  {entry}");
    }
}

Output:

pay 42.00  -> True
pay 250.00 -> False
pay -5.00  -> False
pay 12.50  -> True
audit trail (4 entries):
  09:30 charged 42.00 via stripe-sim ref REF-001
  09:30 declined 250.00 via stripe-sim
  09:30 rejected -5.00: not positive
  09:30 charged 12.50 via stripe-sim ref REF-002

Every timestamp is 09:30 because the clock was frozen, which is the only way an assertion about a log line can be stable. The reference numbers skip REF-002 for the declined charge because FakeGateway returns before incrementing — a detail you can only test because the gateway is yours. Swap in a StripeGateway in production and CheckoutService is not recompiled, let alone rewritten; in ASP.NET Core you register the swap once, services.AddScoped<IPaymentGateway, StripeGateway>(), and the framework does the wiring.


Common Mistakes

  1. Declaring an interface for something that has exactly one implementation and always will. IUserServiceFactoryProvider with one implementer is ceremony, not design. Extract the interface when the second implementation (or the test double) actually arrives.
  2. Putting an access modifier on an explicit implementation. public void IFile.Close() is CS0106; explicit members take no modifier and are never public on the class.
  3. Expecting a default interface member on the class. new Circle(1.0).Describe() will not compile even though IShape supplies a body; you must be looking at the value through the interface.
  4. Adding a member to a published interface. Every implementer in every consuming assembly breaks. Add a default body, or ship a second interface (IShape2) the way the framework does.
  5. Fat contracts. Forcing ScaleBy onto every IShape guarantees implementations that throw. Split the capability out instead.
  6. Storing state in a "stateless" interface via static fields. An interface's static field is shared across every implementer in the process — almost never what you meant.
  7. Returning IEnumerable<T> from something already materialised. Callers cannot count it without walking it, and a lazy query may be enumerated twice. Return IReadOnlyList<T> when you are handing back a finished list.
  8. Casting with (IScalable)shape when you are not sure. That throws InvalidCastException; shape is IScalable s tests and binds in one step, and as gives you null to check.

Best Practices

  • Name interfaces for the capability, prefixed with I: IDisposable, IAuditLog, IScalable. If the best name you can find is IThingManager, the contract probably does too much.
  • Depend on interfaces in constructor parameters, and let something else decide what to pass. That is dependency injection in one sentence, and it is what made the checkout above testable.
  • Accept the least specific type you can use (IEnumerable<T> for a parameter you only foreach) and return the most useful (IReadOnlyList<T> over IEnumerable<T> for a finished collection).
  • Keep interfaces small enough that every implementer honours all of it. Two three-member interfaces beat one six-member interface with holes.
  • Implement IComparable<T> and IEquatable<T> on value-like types so sorting, Distinct and dictionary lookups behave without you writing comparers.
  • Use a generic constraint rather than an interface parameter in hot paths: where T : IComparable<T> avoids the boxing that IComparable costs on structs.
  • Reserve default implementations for versioning an interface you have already shipped, not for sharing real logic — that is an abstract base class's job.
  • Combine both tools: an abstract base for the shared machinery of one family, interfaces for the capabilities that family shares with unrelated types.

Practice Exercises

  1. Define interface INotifier { string Channel { get; } void Send(string message); } and implement it three times — EmailNotifier, SmsNotifier and ConsoleNotifier, the last simply printing. Put all three in a List<INotifier>, loop once and send the same message, printing "[channel] message" from each.
  2. Write class Temperature : IComparable<Temperature>, IEquatable<Temperature> wrapping a decimal Celsius. Implement both interfaces, then build an array of five temperatures, Array.Sort it, and show that Array.IndexOf finds an equal-but-distinct instance — proving IEquatable<T> is being used.
  3. Create interface IReader { string Read(); } and interface IWriter { void Write(string text); }, then a MemoryDocument class implementing both over a private string. Write a method static void Copy(IReader from, IWriter to) and use it to copy between two documents, proving the method needs neither concrete type.
  4. Take the Bridge collision example and extend it: add a third interface IStream that also declares Close(), implement all three explicitly, and write a loop over object[] views = { (IFile)b, (ISocket)b, (IStream)b } that calls the right Close on each via pattern matching. Then add a public Close() on the class itself and explain in a comment which of the four gets called by b.Close().