Skip to content
LumenaryAcademy
Practice 60 min

Interfaces and generics

Writing code against contracts instead of concrete classes, and writing it once for many types.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Depending on what, not on who

A shop's checkout needs a shipping price. It could call the national post office's rate table directly, but then adding a courier means editing the checkout, and testing the checkout means involving the post office's rules. Better: the checkout asks anything that can quote a shipping rate. The post office, two couriers, and a fake rate used in tests all qualify. The checkout depends on a contract, not on a particular company.

In C#, a contract is an interface. The other half of this lesson is about a different kind of reuse. A ring buffer of temperatures and a ring buffer of web pages are the same code with a different element type; so is "find the largest" over numbers, words or version numbers. Generics let you write that code once, with full type safety and, for value types, no loss of speed.

DefinitionsH

Interfaces

Definition— Interface

A named set of members (methods, properties, events, indexers) that a class or struct promises to provide. An interface says what can be done; each implementing type decides how. A type can implement any number of interfaces, and a variable of an interface type can hold any object whose type implements it.

Interface names start with I by convention. Here is the checkout's problem, solved:

csharp
// Code that depends on an interface works with any implementation.
List<IShippingRate> carriers = [new PostOffice(), new Courier("Swift", 9.50m, 1.10m), new Courier("Atlas", 1.50m, 2.50m)];

foreach (decimal kg in new[] { 0.5m, 3m, 12m })
{
    IShippingRate best = Cheapest(carriers, kg);
    Console.WriteLine($"{kg,4} kg: {best.Carrier,-11} {best.Quote(kg),6:F2}  ({best.Describe(kg)})");
}

static IShippingRate Cheapest(IEnumerable<IShippingRate> options, decimal kg)
{
    IShippingRate? best = null;
    foreach (var option in options)
    {
        if (best is null || option.Quote(kg) < best.Quote(kg)) best = option;
    }
    return best ?? throw new ArgumentException("No carriers given.", nameof(options));
}

interface IShippingRate
{
    string Carrier { get; }
    decimal Quote(decimal kilograms);

    // A default interface method (C# 8): implementers get it for free.
    string Describe(decimal kilograms) => $"{Quote(kilograms) / kilograms:F2} per kg";
}

sealed class PostOffice : IShippingRate
{
    public string Carrier => "Post Office";
    public decimal Quote(decimal kilograms) => kilograms <= 1 ? 2.50m : 2.50m + (kilograms - 1) * 4.00m;
}

sealed class Courier(string name, decimal baseFee, decimal perKg) : IShippingRate
{
    public string Carrier => name;
    public decimal Quote(decimal kilograms) => baseFee + kilograms * perKg;
}

It prints:

text
 0.5 kg: Post Office   2.50  (5.00 per kg)
   3 kg: Atlas         9.00  (3.00 per kg)
  12 kg: Swift        22.70  (1.89 per kg)

Cheapest knows nothing about post offices or couriers. It accepts an IEnumerable of IShippingRate, the most general "sequence of things", so callers may pass a list, an array or a query. Adding a third courier means writing one new class; nothing else changes.

Describe has a body inside the interface: a default interface method (C# 8). Implementations inherit it unless they provide their own. Default methods exist mainly so library authors can add a member to a published interface without breaking every existing implementation. Note one quirk: the default is reachable through the interface type. best.Describe(kg) works because best is an IShippingRate; on a variable of type Courier, Describe would not be found.

The IShippingRate? best = null and best is null lines use a nullable annotation and a pattern; both are explained in the next lesson. ?? throw throws if the left side is null, a compact guard.

Why this is how professional C# is structured

Interfaces are the backbone of testable C#. A class that needs a clock, a database or an email sender takes an interface for each in its constructor:

csharp
public sealed class ReminderService(IClock clock, IEmailSender email)
{
    public void SendDueReminders(IEnumerable<Invoice> invoices) { ... }
}

In production, an application's dependency injection container (built into ASP.NET Core and the generic host) creates the real implementations and passes them in. In a unit test, you pass a fake clock fixed at a chosen date and an email sender that records what it was asked to send. .NET 8 even added a standard abstract clock, TimeProvider, for exactly this purpose.

The interfaces the library speaks

Many language and library features work through interfaces you implement:

InterfaceImplement it toUsed by
IEnumerable (of any element type)be iteratedforeach, LINQ, collection constructors
IComparable (of your own type)define a natural orderList.Sort, Array.Sort, SortedSet, Order()
IEquatable (of your own type)define equality without boxingDictionary, HashSet, Contains
IDisposablerelease resources deterministicallyusing statements (the exceptions lesson)

Here a version number type implements IComparable so the library can sort it, and a generic method finds the largest item of any comparable type:

csharp
// IComparable<T> lets the library sort your own type.
List<Release> releases = [new(2, 10, 1), new(10, 0, 0), new(2, 9, 12), new(1, 0, 0)];
releases.Sort();
Console.WriteLine(string.Join("  ", releases));
Console.WriteLine($"Newest: {Largest(releases)}");
Console.WriteLine($"Largest word: {Largest(["kiwi", "mango", "apple"])}");

// A generic method with a constraint: T must know how to compare itself.
static T Largest<T>(IEnumerable<T> items) where T : IComparable<T>
{
    using var e = items.GetEnumerator();
    if (!e.MoveNext()) throw new ArgumentException("Empty sequence.", nameof(items));
    T best = e.Current;
    while (e.MoveNext())
    {
        if (e.Current.CompareTo(best) > 0) best = e.Current;
    }
    return best;
}

readonly record struct Release(int Major, int Minor, int Patch) : IComparable<Release>
{
    public int CompareTo(Release other) =>
        Major != other.Major ? Major.CompareTo(other.Major)
        : Minor != other.Minor ? Minor.CompareTo(other.Minor)
        : Patch.CompareTo(other.Patch);

    public override string ToString() => $"{Major}.{Minor}.{Patch}";
}

It prints:

text
1.0.0  2.9.12  2.10.1  10.0.0
Newest: 10.0.0
Largest word: mango

Sorting the versions as strings would have put 10.0.0 before 2.9.12 and 2.10.1 before 2.9.12; comparing the numbers field by field gives the right order. CompareTo returns a negative number, zero or a positive number for "less", "equal" and "greater".

Worked examplesH

Generic methods and classes

Largest above is a generic method. The T in angle brackets after its name is a type parameter: a placeholder that each call fills in with a real type (Release, then string). The compiler usually infers it from the arguments. The where clause is a constraint: it promises that whatever T is, it implements IComparable of itself, which is what makes e.Current.CompareTo(best) legal inside the method. Without the constraint, the compiler would know nothing about T beyond what every object has, and calling Largest with an array of plain objects is rejected at compile time for exactly this reason.

The common constraints are:

ConstraintMeans T must be
where T : SomeInterface or where T : SomeBaseClassthat interface or class, or derived from it
where T : class / where T : structa reference type / a non-nullable value type
where T : notnulla non-nullable type
where T : new()a type with a public parameterless constructor
where T : unmanageda value type containing no references (for low-level code)

A generic class takes type parameters too. This ring buffer keeps only the most recent items, overwriting the oldest, which is useful for "the last 100 log lines" or "the last five sensor readings":

csharp
// A generic class: a fixed-size buffer that keeps only the most recent items.
var lastReadings = new RingBuffer<double>(3);
foreach (double t in new[] { 21.5, 22.0, 23.1, 22.8, 24.4 })
{
    lastReadings.Add(t);
}
Console.WriteLine($"Last {lastReadings.Count}: {string.Join(", ", lastReadings)}");

var recentPages = new RingBuffer<string>(2);
recentPages.Add("/home");
recentPages.Add("/courses");
recentPages.Add("/courses/csharp");
foreach (string page in recentPages) Console.WriteLine(page);

// Generics are reified: the type argument exists at run time.
Console.WriteLine(Describe(lastReadings));
Console.WriteLine(Describe(recentPages));

static string Describe<T>(RingBuffer<T> buffer) => $"RingBuffer of {typeof(T).Name} holding {buffer.Count}";

sealed class RingBuffer<T>(int capacity) : IEnumerable<T>
{
    private readonly T[] _items = new T[capacity];
    private int _start;

    public int Count { get; private set; }

    public void Add(T item)
    {
        int end = (_start + Count) % _items.Length;
        _items[end] = item;
        if (Count < _items.Length) Count++;
        else _start = (_start + 1) % _items.Length;
    }

    // An iterator: yield return produces the sequence lazily, one item at a time.
    public IEnumerator<T> GetEnumerator()
    {
        for (int i = 0; i < Count; i++)
        {
            yield return _items[(_start + i) % _items.Length];
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}

It prints:

text
Last 3: 23.1, 22.8, 24.4
/courses
/courses/csharp
RingBuffer of Double holding 3
RingBuffer of String holding 2

Three ideas are packed into this program.

Implementing IEnumerable makes a type a sequence. Because RingBuffer implements it, foreach works on it, string.Join accepts it, and so will every LINQ operator in the lesson after next. The last line implements the old non-generic version of the interface, which the generic one extends; it simply forwards to the generic method. (This is called an explicit interface implementation: the member is reachable only through the interface.)

yield return writes an iterator. The compiler turns GetEnumerator into a small state machine. Nothing runs when the method is called; each time the consumer asks for the next item, the method runs until the next yield return, hands over that item, and pauses. Exercise 3 makes this laziness visible.

Generics in .NET are reified. Unlike Java, where type arguments are erased after compilation, .NET keeps them at run time: typeof(T) inside Describe really is Double or String. The JIT generates specialised machine code for each value-type argument, so a RingBuffer<double> stores raw doubles in a double[], with no boxing and no casts. That is why generic collections replaced the old ArrayList, which stored everything as object.

The collection interfaces

The collections from the previous lesson implement a small hierarchy of interfaces, and choosing the right one for a parameter or a return type is a daily decision:

InterfacePromisesTypical use
IEnumerable<string>can be iterated, perhaps only once, perhaps lazilyparameters that only loop over the input
IReadOnlyCollection<string>iterable, and knows its Countwhen you need the size up front
IReadOnlyList<string>indexable by position, read-onlyparameters and return values that callers must not modify
ICollection<string>, IList<string>can add and removerarely in public signatures; usually just take or return List<string>
IReadOnlyDictionary<string, int>look-up by key, read-onlyexposing a dictionary without letting callers change it

Two habits follow. When a method returns data it owns, such as a class exposing its internal list, return an IReadOnlyList (or a copy), so callers cannot change the object's state behind its back. And when a method takes an IEnumerable, remember it might be a lazy query that does work, or even reads a database, each time it is iterated; if you need to walk it twice, copy it to a list first. The LINQ lesson returns to this.

Interfaces themselves should be small. An interface with one or two members (IShippingRate, IClock, IComparable) is easy to implement, easy to fake, and says exactly what a consumer needs. A twenty-member IOrderManager forces every implementation, including test doubles, to provide all twenty.

Variance, briefly

Can an IEnumerable<string> be used where an IEnumerable<object> is expected? Yes: every string is an object, and a sequence only hands items out. Interfaces mark such type parameters out (covariant). A List<string> cannot be used as a List<object>, though, because you could then add a number to a list of strings. Most of the time this just works and you never think about it; when the compiler refuses a conversion between two generic types, variance is usually why.

Worked examplesH

Generic math and extension members

For years you could not write one Sum method for int, double and decimal, because operators like + are static and interfaces could not describe static members. C# 11 added static abstract interface members, and .NET 7 used them to describe numbers: INumber and its relatives in System.Numerics declare +, /, Zero, One and conversions. Every built-in numeric type implements them.

The second half of this program uses extension members. An extension lets you call a method on a type as though the type had declared it, without modifying or inheriting from it. Classic extension methods (C# 3) are static methods whose first parameter is marked this; LINQ is built from them. C# 14 adds extension blocks, which can also declare extension properties and static members:

csharp
using System.Numerics;

// Generic math (C# 11, .NET 7): one method for every numeric type.
Console.WriteLine(Mean<int>([3, 4, 8]));
Console.WriteLine(Mean<double>([2.5, 3.5]));
Console.WriteLine(Mean<decimal>([0.1m, 0.2m, 0.3m]));

static T Mean<T>(ReadOnlySpan<T> values) where T : INumber<T>
{
    T sum = T.Zero;
    foreach (T v in values) sum += v;
    return sum / T.CreateChecked(values.Length);
}

// Extension members (C# 14): add properties and methods to types you do not own.
Console.WriteLine("racecar".IsPalindrome);
Console.WriteLine("Lumenary".IsPalindrome);
Console.WriteLine("hello world".ToTitleCase());
Console.WriteLine(string.Join(",", Enumerable.Range(1, 10).EveryNth(3)));

static class TextExtensions
{
    extension(string text)
    {
        public bool IsPalindrome
        {
            get
            {
                for (int i = 0, j = text.Length - 1; i < j; i++, j--)
                {
                    if (char.ToLowerInvariant(text[i]) != char.ToLowerInvariant(text[j])) return false;
                }
                return true;
            }
        }

        public string ToTitleCase() =>
            string.Join(' ', text.Split(' ').Select(w => w.Length == 0 ? w : char.ToUpperInvariant(w[0]) + w[1..]));
    }

    // The classic form of extension method (C# 3), still everywhere in .NET code.
    public static IEnumerable<T> EveryNth<T>(this IEnumerable<T> source, int n)
    {
        int i = 0;
        foreach (T item in source)
        {
            if (++i % n == 0) yield return item;
        }
    }
}

It prints:

text
5
3
0.2
True
False
Hello World
3,6,9

Inside Mean, T.Zero and T.CreateChecked(...) call static members through the type parameter, which is exactly what static abstract members make possible. CreateChecked converts the count to T, throwing if it does not fit. Notice that Mean<int> does integer division: the mean of 3, 4 and 8 is exactly 5 here, but generic code does whatever T's operators do.

extension(string text) { ... } declares a block of members that extend string; inside it, text is the receiver. Both forms of extension compile to static methods, and the compiler simply rewrites "racecar".IsPalindrome into a call. So extensions cannot see private members of the type they extend, and they cannot add state.

When is an extension the right tool? When you want a fluent helper on a type you do not own (a string, an interface, a library's class), or when you want behaviour available on every implementation of an interface, as LINQ does for every IEnumerable. When the type is yours, add a real method. And be sparing: an extension called ToTitleCase on every string in the codebase is something every colleague now has to know about.

Common misconceptionsH

Common misconceptions

Misconception

"Every class should have an interface." An interface earns its keep when there are, or will be, several implementations, or when code must be tested without the real thing (time, network, disk, randomness). An IInvoiceCalculator with exactly one implementation and nothing to fake is ceremony. Introduce the interface when the second implementation or the test appears.

Misconception

"Generics are slow because of boxing." That was true of the old non-generic collections, which stored object. .NET generics are specialised per value type by the JIT, so a List<int> stores plain ints and runs as fast as hand-written code.

Misconception

"An iterator method runs when I call it." Calling a method that uses yield return only creates the sequence. Its body runs piece by piece as the sequence is enumerated, and runs again from the start each time you enumerate it again. Argument checks inside an iterator therefore happen late; libraries put them in a separate, non-iterator method that then calls the iterator.

Exercises

Exercises

1. Interfaces and generics

Warm-upHuman

The lesson's Largest method is declared static T Largest<T>(IEnumerable<T> items) where T : IComparable<T>. Which call fails to compile?

Choose one

2. Interfaces and generics

StretchComputational

What does the first line of output of this program read?

Console.WriteLine(typeof(List<int>).Name);
Console.WriteLine(typeof(Dictionary<string, int>).Name);

3. Interfaces and generics

CoreComputational

What does this program print? (Console.Write does not add a new line.)

static IEnumerable<int> Numbers()
{
    Console.Write("A");
    yield return 1;
    Console.Write("B");
    yield return 2;
    Console.Write("C");
}

foreach (int n in Numbers()) Console.Write(n);
Console.WriteLine();

4. Interfaces and generics

CoreComputational

Using the lesson's generic Mean method (T sum = T.Zero; ...; return sum / T.CreateChecked(values.Length);), what does this line print?

Console.WriteLine(Mean<int>([1, 2]) + Mean<double>([1, 2]));

5. Interfaces and generics

CoreComputational

What does this program print?

IGreeter g = new Polite();
Console.WriteLine(g.Greet("Ama"));

interface IGreeter
{
    string Name { get; }
    string Greet(string who) => $"Hi {who}, I'm {Name}";
}

class Polite : IGreeter
{
    public string Name => "Polite";
    public string Greet(string who) => $"Good evening, {who}";
}

6. Interfaces and generics

CoreHuman

Which statements about extension members (classic extension methods and C# 14 extension blocks) are true? (Choose all that apply.)

Choose all that apply

7. Interfaces and generics

CoreComputational

Using the lesson's RingBuffer, what does this print?

var buffer = new RingBuffer<int>(2);
for (int i = 1; i <= 5; i++) buffer.Add(i);
Console.WriteLine(string.Join(",", buffer));

Further reading and resources

  • Interfaces · MicrosoftDefining, implementing and using interfaces.
  • Generics in .NET · MicrosoftHow generics work in the runtime, constraints, and variance.
  • Generic math · MicrosoftINumber and the other numeric interfaces introduced in .NET 7.
  • Extension members · MicrosoftClassic extension methods and the extension blocks added in C# 14.