Tutorials / Advanced C# and .NET / Generics and constraints

Generics and constraints

14 min read csharp
Course contents (16 lessons)
  1. The type system
  2. Records, structs and value equality
  3. Interfaces and abstract classes
  4. Generics and constraints
  5. Delegates, events and lambdas
  6. Querying and matching data
  7. LINQ in depth: deferred execution, grouping and joins
  8. IEnumerable versus IQueryable
  9. Pattern matching in modern C#
  10. Async and await: how Task really works
  11. Async patterns: cancellation, timeouts and async streams
  12. Application structure
  13. Dependency injection and service lifetimes
  14. Configuration, options and logging
  15. Data and web
  16. Entity Framework Core basics: DbContext, migrations and queries
  17. Building a minimal API with ASP.NET Core
  18. Unit testing with xunit
  19. Performance and the final project
  20. Performance basics: Span of T and fewer allocations
  21. Final project: a notes API with EF Core, DI and logging

One piece of code, many types

You have used List<int> and List<string>. Both come from the same class, List<T>. The T is a type parameter. It is a placeholder that gets replaced when you use the class. Generics let you write logic once and use it with any type, and the compiler still checks types for you.

Before generics, collections stored object. You cast on the way out, and a wrong cast crashed at runtime. Value types were also boxed into heap objects. Generics removed both problems.

A generic class

Here is a small Result<T>. Instead of throwing exceptions for expected failures, such as "user not found", a method can return a result that is either a value or an error message. I find this style makes code honest about what can fail.

Result<int> parsed = ParseAge("34");
Console.WriteLine(parsed.IsSuccess ? $"Age is {parsed.Value}" : parsed.Error);

Result<int> bad = ParseAge("abc");
Console.WriteLine(bad.IsSuccess ? $"Age is {bad.Value}" : bad.Error);

// Generic method with a constraint
Console.WriteLine(Largest(new[] { 3, 9, 2 }));
Console.WriteLine(Largest(new[] { "pear", "apple", "zebra" }));

// A generic repository over any entity with an Id
var repo = new InMemoryRepository<Product>();
repo.Add(new Product(1, "Keyboard"));
repo.Add(new Product(2, "Mouse"));
Console.WriteLine(repo.GetById(2)?.Name);
Console.WriteLine(repo.GetById(99)?.Name ?? "not found");

// Transform a list with a generic helper
var lengths = Map(new[] { "a", "bbb", "cc" }, s => s.Length);
Console.WriteLine(string.Join(",", lengths));

static Result<int> ParseAge(string text)
{
    if (int.TryParse(text, out int age) && age is >= 0 and <= 130)
    {
        return Result<int>.Ok(age);
    }
    return Result<int>.Fail($"'{text}' is not a valid age.");
}

static T Largest<T>(IEnumerable<T> items) where T : IComparable<T>
{
    T best = items.First();
    foreach (T item in items)
    {
        if (item.CompareTo(best) > 0) best = item;
    }
    return best;
}

static List<TOut> Map<TIn, TOut>(IEnumerable<TIn> source, Func<TIn, TOut> selector)
{
    var result = new List<TOut>();
    foreach (TIn item in source) result.Add(selector(item));
    return result;
}

class Result<T>
{
    public bool IsSuccess { get; }
    public T Value { get; }
    public string Error { get; }

    private Result(bool ok, T value, string error)
    {
        IsSuccess = ok;
        Value = value;
        Error = error;
    }

    public static Result<T> Ok(T value) => new(true, value, "");
    public static Result<T> Fail(string error) => new(false, default!, error);
}

interface IEntity
{
    int Id { get; }
}

record Product(int Id, string Name) : IEntity;

class InMemoryRepository<T> where T : class, IEntity
{
    private readonly Dictionary<int, T> _items = new();

    public void Add(T item) => _items[item.Id] = item;
    public T? GetById(int id) => _items.TryGetValue(id, out T? item) ? item : null;
}

Walking through it

Result<T> has a private constructor and two static factory methods, Ok and Fail. The only way to build one is through a factory, so a result is always either a success with a value or a failure with a message. The default! in Fail says "no real value here", and the exclamation mark silences the nullable warning for that one line. The type of Value changes with each use: Result<int> holds an int, Result<User> would hold a user.

The method Largest<T> has a constraint: where T : IComparable<T>. Without it, the compiler would not let us call CompareTo, because T could be anything. The constraint says "T must know how to compare itself". Integers and strings both do, so the same method works for both. If you pass a type that cannot compare itself, you get a compile error, not a runtime crash.

The Map method has two type parameters. The compiler infers both from the arguments, so we call it without writing the angle brackets. This is the same idea as the LINQ method Select.

The repository has the constraint where T : class, IEntity. That means T must be a reference type and must implement IEntity, so we can read item.Id. The class constraint also lets us return null from GetById to mean "not found". The compiler knows null is meaningful for T here.

Useful constraints

  • where T : class or struct limits T to reference or value types.
  • where T : new() requires a public parameterless constructor, so you can write new T().
  • where T : SomeBase or SomeInterface lets you use that type's members.
  • where T : notnull keeps null out of the type argument.

Common mistakes

  • Making everything generic. If a method only ever handles Order, keep it simple. Generics are for real reuse.
  • Missing constraints and then trying to cast inside the method. That throws away the safety generics give you.
  • Generic repositories that hide the database. A repository over T with GetAll often forces you to load too much data. Be careful with this pattern when you reach EF Core.
  • Expecting static fields to be shared. Cache<int> and Cache<string> each have their own static fields.

Try it yourself

  1. Write a generic method Swap<T>(ref T a, ref T b) and test it with ints and strings.
  2. Write Filter<T>(IEnumerable<T>, Func<T, bool>) without using LINQ.
  3. Create a generic Stack<T> class backed by a List<T> with Push, Pop and Peek. Decide what Pop should do on an empty stack.
csharp
Result<int> parsed = ParseAge("34");
Console.WriteLine(parsed.IsSuccess ? $"Age is {parsed.Value}" : parsed.Error);

Result<int> bad = ParseAge("abc");
Console.WriteLine(bad.IsSuccess ? $"Age is {bad.Value}" : bad.Error);

// Generic method with a constraint
Console.WriteLine(Largest(new[] { 3, 9, 2 }));
Console.WriteLine(Largest(new[] { "pear", "apple", "zebra" }));

// A generic repository over any entity with an Id
var repo = new InMemoryRepository<Product>();
repo.Add(new Product(1, "Keyboard"));
repo.Add(new Product(2, "Mouse"));
Console.WriteLine(repo.GetById(2)?.Name);
Console.WriteLine(repo.GetById(99)?.Name ?? "not found");

// Transform a list with a generic helper
var lengths = Map(new[] { "a", "bbb", "cc" }, s => s.Length);
Console.WriteLine(string.Join(",", lengths));

static Result<int> ParseAge(string text)
{
    if (int.TryParse(text, out int age) && age is >= 0 and <= 130)
    {
        return Result<int>.Ok(age);
    }
    return Result<int>.Fail($"'{text}' is not a valid age.");
}

static T Largest<T>(IEnumerable<T> items) where T : IComparable<T>
{
    T best = items.First();
    foreach (T item in items)
    {
        if (item.CompareTo(best) > 0) best = item;
    }
    return best;
}

static List<TOut> Map<TIn, TOut>(IEnumerable<TIn> source, Func<TIn, TOut> selector)
{
    var result = new List<TOut>();
    foreach (TIn item in source) result.Add(selector(item));
    return result;
}

class Result<T>
{
    public bool IsSuccess { get; }
    public T Value { get; }
    public string Error { get; }

    private Result(bool ok, T value, string error)
    {
        IsSuccess = ok;
        Value = value;
        Error = error;
    }

    public static Result<T> Ok(T value) => new(true, value, "");
    public static Result<T> Fail(string error) => new(false, default!, error);
}

interface IEntity
{
    int Id { get; }
}

record Product(int Id, string Name) : IEntity;

class InMemoryRepository<T> where T : class, IEntity
{
    private readonly Dictionary<int, T> _items = new();

    public void Add(T item) => _items[item.Id] = item;
    public T? GetById(int id) => _items.TryGetValue(id, out T? item) ? item : null;
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account