C# · Lesson 4
Generics, interfaces & delegates
Interfaces and why C# typing is nominal, generic types and methods with constraints, covariance and contravariance, extension methods, IComparable/IEquatable/IComparer, delegates and lambdas (Func, Action, Predicate, closures) and events, next to their TypeScript equivalents.
In short
- Interfaces are nominal: a class must declare
: IClock - Generics are real at runtime:
typeof(T),default where T : IComparable<T>is TypeScript'sextends- Extension methods:
thison the first parameter Func,ActionandPredicateare function types- Lambdas capture variables, not values
Open any ASP.NET Core project and the first thing you see is interfaces and generics:
builder.Services.AddScoped<IOrderRepository, SqlOrderRepository>(), ILogger<OrderService>,
IOptions<StorageOptions>, Task<IReadOnlyList<Order>>, and LINQ, which is generic extension methods all
the way down. Generics will feel familiar from TypeScript. Interfaces look the same but follow a different
rule. And delegates are C#'s typed function values, the glue behind LINQ lambdas, callbacks and events.
Interfaces are nominal
IClock clock = new FixedClock(new DateTimeOffset(2024, 1, 1, 9, 0, 0, TimeSpan.Zero));
var greeter = new Greeter(clock);
Console.WriteLine(greeter.Greet("Ada"));
public interface IClock
{
DateTimeOffset Now { get; }
}
public sealed class SystemClock : IClock
{
public DateTimeOffset Now => DateTimeOffset.UtcNow;
}
public sealed class FixedClock(DateTimeOffset now) : IClock // a test double
{
public DateTimeOffset Now => now;
}
public sealed class Greeter(IClock clock)
{
public string Greet(string name) => clock.Now.Hour < 12 ? $"Good morning, {name}" : $"Hello, {name}";
}
interface Clock { now(): Date }
class FixedClock { constructor(private readonly at: Date) {} now() { return this.at; } }
const clock: Clock = new FixedClock(new Date('2024-01-01T09:00:00Z')); // fine: same shape
console.log(clock.now().toISOString());
TypeScript is structural: anything with the right shape fits an interface. C# is nominal: a class
fits IClock only if it declares : IClock. A class with a matching Now property but no declaration
is not an IClock. That's stricter, but it means "implements" is a deliberate, searchable decision, and the
runtime knows about it (clock is IClock).
- Interfaces hold method, property, event and indexer signatures. By convention their names start with
I. - A class can implement many interfaces but inherit from only one class.
- Interfaces are how .NET code gets dependency injection and testability:
Greeterdepends onIClock, production registersSystemClock, and the test passes aFixedClock. (Since .NET 8 the BCL has a built-in abstraction for exactly this,TimeProvider, withFakeTimeProviderfrom theMicrosoft.Extensions.TimeProvider.Testingpackage for tests. Prefer it to a home-madeIClockin new code.) - Explicit implementation (
DateTimeOffset IClock.Now => ...) hides a member unless you go through the interface. You'll see it when a class implements two interfaces with clashing members, or forIEnumerable.GetEnumerator(). - Interfaces can contain default method bodies and static members, but most code keeps them as pure contracts.
Generics
var ints = new Box<int>(42);
var name = new Box<string>("Ada");
Console.WriteLine($"{ints.Value + 1} {name.Value.ToUpper()}");
Console.WriteLine(First(new[] { "x", "y" })); // T inferred as string
Console.WriteLine(First(Array.Empty<int>())); // default(int) is 0
Console.WriteLine(Describe(3.5));
Console.WriteLine(Describe(new List<int>()));
static T? First<T>(IReadOnlyList<T> items) => items.Count > 0 ? items[0] : default;
static string Describe<T>(T value) => $"{typeof(T).Name}: {value}"; // T is real at runtime
public sealed class Box<T>(T value)
{
public T Value { get; } = value;
}
class Box<T> { constructor(readonly value: T) {} }
function first<T>(items: readonly T[]): T | undefined { return items[0]; }
console.log(new Box(42).value + 1, first(['x', 'y']));
The syntax is nearly identical, and type arguments are inferred from method arguments the same way. The big difference is underneath: TypeScript erases generics, while .NET keeps them at runtime.
typeof(T)works,x is Tworks, andList<int>really is a list of 32-bit integers (no boxing), which is a different type fromList<string>.default(T)(or justdefault) is "the zero value of T":0,false,null. Note theT?onFirst: for an unconstrainedT,T?means "may be default".- Each closed generic type is its own type with its own static fields:
Cache<User>andCache<Order>don't share statics.ILogger<OrderService>reads the real type argument to give every class its own logger category.
Constraints
Inside a generic method you can only use what every possible T supports. A constraint narrows T
so you can do more with it, like extends in TypeScript:
Console.WriteLine(Largest([3, 9, 4]));
Console.WriteLine(Largest(["pear", "apple", "plum"]));
Console.WriteLine(Sum([1.5m, 2.25m]));
var widget = Create<Widget>();
Console.WriteLine(widget.Name);
static T Largest<T>(IEnumerable<T> items) where T : IComparable<T>
{
using var e = items.GetEnumerator();
if (!e.MoveNext()) throw new InvalidOperationException("No items");
T max = e.Current;
while (e.MoveNext())
if (e.Current.CompareTo(max) > 0) max = e.Current; // CompareTo is allowed thanks to the constraint
return max;
}
static T Sum<T>(IEnumerable<T> items) where T : System.Numerics.INumber<T>
{
T total = T.Zero; // static abstract interface members (generic math)
foreach (var x in items) total += x;
return total;
}
static T Create<T>() where T : new() => new T();
public class Widget { public string Name { get; set; } = "default widget"; }
| Constraint | Means | TypeScript analogue |
|---|---|---|
where T : IComparable<T> | T implements the interface | T extends Comparable<T> |
where T : Shape | T is Shape or a subclass | T extends Shape |
where T : class / class? | T is a reference type (non-nullable / nullable) | T extends object |
where T : struct | T is a non-nullable value type | |
where T : notnull | T is a non-nullable type (good for dictionary keys) | T extends {} |
where T : new() | T has a public parameterless constructor | new () => T |
where T : INumber<T> | generic math: +, T.Zero, comparisons (.NET 7+) |
Combine them with commas (where T : class, IEntity, new()), and constrain each type parameter separately
(where TKey : notnull where TValue : class).
Covariance and contravariance
Is a list of strings a list of objects? It depends on what you can do with it:
IEnumerable<string> names = new List<string> { "Ada", "Grace" };
IEnumerable<object> things = names; // OK: IEnumerable<out T> only hands Ts out
Console.WriteLine(things.Count());
// List<object> list = new List<string>(); // error CS0029: List<T> also takes Ts in (Add)
Action<object> logAnything = o => Console.WriteLine($"log: {o}");
Action<string> logString = logAnything; // OK: Action<in T> only takes Ts in
logString("hello");
object[] array = new string[1]; // arrays are covariant (a legacy decision)...
try { array[0] = 42; } // ...so the check happens at runtime instead
catch (ArrayTypeMismatchException) { Console.WriteLine("ArrayTypeMismatchException"); }
- Covariant (
out T): the type only produces T values, so a producer of strings can stand in for a producer of objects.IEnumerable<out T>,IReadOnlyList<out T>,Func<out TResult>... AnIEnumerable<Dog>is anIEnumerable<Animal>.Task<T>is a class, and only interfaces and delegates can be variant, so aTask<string>is not aTask<object>. - Contravariant (
in T): the type only consumes T values, so something that handles any object can handle strings.Action<in T>,IComparer<in T>,IEqualityComparer<in T>. AnIComparer<Animal>can sort dogs. - Invariant:
List<T>,IList<T>,Dictionary<TKey, TValue>both take and return T, so neither direction is safe. - Variance only works for reference types. An
IEnumerable<int>is not anIEnumerable<object>, because eachintwould have to be boxed. - TypeScript checks arrays covariantly at compile time and never at runtime, which is unsound
(
const a: object[] = strings; a.push(42)compiles). C# makes you pick a read-only interface to get covariance.
The practical rule: accept IEnumerable<T> or IReadOnlyList<T> in parameters, and callers can pass a
list of a more specific type for free.
Extension methods
An extension method is a static method that you can call as if it were an instance method. It's how LINQ
adds Where and Select to every IEnumerable<T>:
string? missing = null;
Console.WriteLine(missing.IsBlank()); // True: works on null, it's just a static call
Console.WriteLine("Hello World".Truncate(8));
Console.WriteLine(string.Join(",", new[] { 1, 2, 3, 4 }.EveryOther()));
Console.WriteLine(StringExtensions.Truncate("Hello World", 8)); // what the compiler really calls
public static class StringExtensions
{
public static bool IsBlank(this string? value) => string.IsNullOrWhiteSpace(value);
public static string Truncate(this string value, int max) =>
value.Length <= max ? value : value[..(max - 1)] + "…";
}
public static class EnumerableExtensions
{
public static IEnumerable<T> EveryOther<T>(this IEnumerable<T> source)
{
bool take = true;
foreach (var item in source)
{
if (take) yield return item;
take = !take;
}
}
}
- The method lives in a static class, and its first parameter has
thisin front of it. - It's found through
usingthe namespace of the static class. IfWhere"doesn't exist", you're missingusing System.Linq;(implicit usings include it). - It can't access private members. It's syntax, not a way into the class.
- Extending an interface (
this IEnumerable<T>) or a generic constraint gives every implementation the method. ASP.NET Core'sservices.AddScoped(...),app.MapGet(...)andbuilder.Services.AddDbContext(...)are all extension methods on interfaces. - TypeScript would need you to patch a prototype, or write a free function. C# makes the free function look like a method without touching the type.
Comparing and equating: IComparable, IComparer, IEquatable
.NET's sorting and hashing APIs all go through a few small interfaces:
var versions = new List<Version3> { new(1, 10, 0), new(1, 2, 3), new(1, 2, 0) };
versions.Sort(); // uses IComparable<Version3>
Console.WriteLine(string.Join(" < ", versions));
Console.WriteLine(versions.Max()); // also uses CompareTo
var byLength = Comparer<string>.Create((a, b) => a.Length.CompareTo(b.Length));
var words = new List<string> { "ccc", "a", "bb" };
words.Sort(byLength); // an IComparer<string> from a lambda
Console.WriteLine(string.Join(",", words));
var tags = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Urgent", "urgent", "URGENT" };
Console.WriteLine(tags.Count); // 1: IEqualityComparer<string>
public readonly record struct Version3(int Major, int Minor, int Patch) : IComparable<Version3>
{
public int CompareTo(Version3 other) =>
(Major, Minor, Patch).CompareTo((other.Major, other.Minor, other.Patch)); // tuples compare in order
public override string ToString() => $"{Major}.{Minor}.{Patch}";
}
| Interface | Question it answers | Used by |
|---|---|---|
IComparable<T> | "how do I compare to another T?" (the natural order) | List.Sort(), Array.Sort, OrderBy(x => x), Max, SortedSet<T> |
IComparer<T> | "how do these two Ts compare?" (an alternative order) | Sort(comparer), OrderBy(key, comparer), SortedDictionary |
IEquatable<T> | "am I equal to another T?" | Dictionary, HashSet, Contains, Distinct (with GetHashCode) |
IEqualityComparer<T> | "are these two Ts equal, and what's the hash?" | new Dictionary<K, V>(comparer), Distinct(comparer) |
CompareTo returns a negative number, zero or a positive number, like a TypeScript sort callback. Records
implement IEquatable<T> for you. Comparison you always write yourself, and comparing tuples is the
shortest way to get "compare by this, then by that".
Delegates and lambdas
A delegate is a typed reference to a method: C#'s function type. You'll mostly use the built-in generic ones:
Func<int, int, int> add = (a, b) => a + b; // takes two ints, returns an int
Action<string> log = message => Console.WriteLine($"[log] {message}"); // returns nothing
Predicate<int> isEven = n => n % 2 == 0; // takes an int, returns bool
Func<string> now = () => "12:00";
log($"{add(2, 3)} {isEven(4)} {now()}");
Func<int, int> square = Square; // a method group: no lambda needed
Console.WriteLine(string.Join(",", new[] { 1, 2, 3 }.Select(square)));
var twice = (int x, int times = 2) => x * times; // a lambda with a natural type and a default parameter
Console.WriteLine(twice(5));
static int Square(int x) => x * x;
const add: (a: number, b: number) => number = (a, b) => a + b;
const log: (message: string) => void = (message) => console.log(`[log] ${message}`);
log(`${add(2, 3)}`);
| TypeScript | C# |
|---|---|
(x: A) => R | Func<A, R> |
(a: A, b: B) => R | Func<A, B, R> (the last type argument is the result) |
(x: A) => void | Action<A> |
() => void | Action |
(x: T) => boolean | Func<T, bool> (LINQ) or Predicate<T> (older List<T> APIs like RemoveAll) |
() => Promise<T> | Func<Task<T>> |
Delegate types are nominal too: a Predicate<int> is not a Func<int, bool>, even though they have the same
shape. A lambda converts to either, but a variable of one type doesn't convert to the other.
Closures capture variables, not values
var actions = new List<Action>();
for (int i = 0; i < 3; i++)
actions.Add(() => Console.Write(i)); // one `i` for the whole loop
foreach (var n in new[] { 0, 1, 2 })
actions.Add(() => Console.Write(n)); // a fresh `n` per iteration
foreach (var action in actions) action();
Console.WriteLine(); // 333012
A lambda captures the variable, and sees its value when the lambda runs. A for loop has one
variable for all iterations, so every lambda prints its final value, 3. foreach creates a new variable
per iteration (since C# 5), so those lambdas print 0, 1, 2. JavaScript's let in a for loop creates a
fresh binding per iteration, which is why this catches TypeScript developers out. Copy the value into a
local inside the loop (int copy = i;) when you need it.
A captured variable lives as long as the lambda does. A lambda stored in a long-lived object (an event
handler, a cache, a singleton) keeps everything it captured alive. Mark a lambda static (static x => x * 2)
when it shouldn't capture anything, and the compiler checks that for you.
Multicast delegates and events
Delegates can hold several methods: += adds one, -= removes one, and invoking calls them all in order.
An event is a delegate field that outsiders can only += and -=:
var sensor = new TemperatureSensor();
EventHandler<double> printer = (sender, celsius) => Console.WriteLine($"now {celsius}°C");
sensor.Changed += printer;
sensor.Changed += (_, celsius) => { if (celsius > 30) Console.WriteLine("too hot!"); };
sensor.Report(21.5);
sensor.Report(31);
sensor.Changed -= printer; // unsubscribe
sensor.Report(35);
// sensor.Changed(sensor, 99); // error CS0070: only the owner can raise it
public sealed class TemperatureSensor
{
public event EventHandler<double>? Changed;
public void Report(double celsius) => Changed?.Invoke(this, celsius); // ?. : no subscribers, no call
}
- The
eventkeyword stops outside code from invoking the delegate or replacing it with=. Only+=and-=are allowed. - The convention is
EventHandler<TArgs>:(object? sender, TArgs args). - Unsubscribe. A publisher holds a reference to every subscriber's handler. A long-lived publisher (a singleton service, a static event) keeps short-lived subscribers alive forever: the classic .NET memory leak.
- If one handler throws, the remaining handlers don't run, and the exception goes to whoever raised the event.
- In application code you'll see fewer raw events than in UI frameworks. Services tend to use
IObservable<T>(Rx.NET),Channel<T>, or a mediator library. The "event bus" exercise builds the core of one.
Common mistakes
- Expecting structural typing. A class with the right members isn't an
IClockunless it says: IClock. - Constraining too little. Without
where T : IComparable<T>, you can't callCompareTo. Withoutnotnull, dictionary keys can be null. - Using
List<T>in signatures.void Print(List<Animal> animals)won't accept aList<Dog>.IEnumerable<Animal>will. - Extension methods everywhere. They're great for fluent helpers and for extending interfaces, but a normal method on your own type is easier to find.
- Capturing a
forloop variable in a lambda that runs later. - Forgetting
-=. Event subscriptions keep subscribers alive. - Throwing from an event handler. It stops the other handlers.
In a real codebase
Side note
// Program.cs of an ASP.NET Core app (not runnable here)
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddScoped<IOrderRepository, SqlOrderRepository>(); // interface -> implementation
builder.Services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>)); // open generic registration
builder.Services.Configure<StorageOptions>(builder.Configuration.GetSection("Storage"));
public interface IRepository<T> where T : class, IEntity
{
Task<T?> FindAsync(Guid id, CancellationToken ct);
Task<IReadOnlyList<T>> ListAsync(Expression<Func<T, bool>> filter, CancellationToken ct);
Task AddAsync(T entity, CancellationToken ct);
}
public sealed class OrderService(IRepository<Order> orders, ILogger<OrderService> logger, IOptions<StorageOptions> options)
{
// ...
}
Interfaces as seams for DI and tests, a generic repository constrained to entities, an open generic
registration, ILogger<T> (a category per class, thanks to generics being real at runtime), and
Expression<Func<T, bool>>: a lambda that EF Core reads as data and translates to SQL. Every piece of this
lesson is in those ten lines.
The exercises
- Generic helpers:
MaxOf,ClampandIsSortedwithwhere T : IComparable<T>. - Extension methods: string helpers that work on
null, plus a genericWhereNotNull. - A fluent validator: a generic class that stores
Funcrules, FluentValidation-style. - Comparable release versions:
IComparable<T>, comparison operators and SemVer ordering rules. - An event bus: generic subscribe and publish with delegates, base-type delivery,
IDisposablesubscriptions and error isolation. - An LRU cache: a generic cache with constraints, a custom comparer, an
Evictedevent and O(1) operations.
Practise this lesson
In the app: a short video, 6 exercises checked by real tests and a 10-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.
Open in the app