Interfaces and composition
Interfaces and composition
An interface describes behavior a type promises to provide. Composition builds an object from cooperating objects instead of extending their classes. A checkout can hold a shipping policy through an interface and ask it for a fee. Changing the policy then changes the calculation without changing the checkout implementation.
using System;IShippingRate rate = new FlatRate();Console.WriteLine(rate.Fee(3));interface IShippingRate{ int Fee(int boxes);}class FlatRate : IShippingRate{ public int Fee(int boxes) => 6;}The FlatRate implementation supplies the interface operation; its fee does not depend on the count.
Expected output (reasoned, not executed):
6Define a contract
An interface with int Fee(int boxes); requires an implementation of that method unless another applicable implementation is provided. A class can implement multiple interfaces. The class uses a public matching member for ordinary implicit implementation. Interface variables can refer to instances of implementing classes. Modern C# also supports default interface implementations and static abstract members; those advanced forms are outside this first contract example.
Separate calculation from policy selection
A constructor parameter of interface type lets the caller supply the dependency. Store that dependency in a private readonly field. The caller decides which implementation to create, while Checkout uses only the agreed operation. This is manual dependency injection: supplying a collaborator from outside rather than building it inside. No container or framework is needed. A readonly reference field cannot be reassigned after construction, but the referenced object can still be mutable. A contract also needs documented meaning: for this example the box count is nonnegative, the result is in whole fee units and the input is small enough to avoid overflow.
using System;Checkout flat = new Checkout(new FlatRate());Checkout perBox = new Checkout(new PerBoxRate());Console.WriteLine(flat.Total(20, 3));Console.WriteLine(perBox.Total(20, 3));interface IShippingRate{ int Fee(int boxes);}class FlatRate : IShippingRate{ public int Fee(int boxes) => 6;}class PerBoxRate : IShippingRate{ public int Fee(int boxes) => 3 * boxes;}class Checkout{ private readonly IShippingRate _rate; public Checkout(IShippingRate rate) => _rate = rate; public int Total(int subtotal, int boxes) => subtotal + _rate.Fee(boxes);}The same checkout class works with two independently chosen rate implementations. Values are synthetic whole units, not financial advice or a production billing model.
Expected output (reasoned, not executed):
2629using System;Label label = new Label();IShortName shortName = label;ILongName longName = label;Console.WriteLine(shortName.Name());Console.WriteLine(longName.Name());interface IShortName { string Name(); }interface ILongName { string Name(); }class Label : IShortName, ILongName{ string IShortName.Name() => "Box"; string ILongName.Name() => "Storage box";}Explicit interface implementations distinguish the two contracts. These methods are accessed through their interface types, not as ordinary public Label.Name methods.
Expected output (reasoned, not executed):
BoxStorage boxCommon mistakes
Do not put new FlatRate() inside Checkout if the goal is to support caller-selected rates. Accept the contract instead. Do not invent an interface for every class: a stable boundary or meaningful alternative is a reason to introduce one. Validate dependencies at public boundaries when callers may supply invalid values.
Practice
Add a FreeShipping implementation to the checkout example. Use the same Checkout class to compute a total for subtotal 20 and three boxes. Explain which source files or class declarations change.
Predict the outcome before checking your work. The separate manual practice and quiz are staged, not automatically graded.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Interfaces and composition — knowledge check
Apply the lesson concepts to the following scenarios.
Which parameter allows a caller to replace a shipping policy?
What is composition in Checkout?
Does a readonly interface field make the policy object immutable?
How do you call an explicitly implemented IShortName.Name on Label?
What is a reason to introduce an interface?