Generics and constraints
Course contents (16 lessons)
- The type system
- Records, structs and value equality
- Interfaces and abstract classes
- Generics and constraints
- Delegates, events and lambdas
- Querying and matching data
- LINQ in depth: deferred execution, grouping and joins
- IEnumerable versus IQueryable
- Pattern matching in modern C#
- Async and await: how Task really works
- Async patterns: cancellation, timeouts and async streams
- Application structure
- Dependency injection and service lifetimes
- Configuration, options and logging
- Data and web
- Entity Framework Core basics: DbContext, migrations and queries
- Building a minimal API with ASP.NET Core
- Unit testing with xunit
- Performance and the final project
- Performance basics: Span of T and fewer allocations
- 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 : classorstructlimits T to reference or value types.where T : new()requires a public parameterless constructor, so you can writenew T().where T : SomeBaseorSomeInterfacelets you use that type's members.where T : notnullkeeps 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
TwithGetAlloften 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>andCache<string>each have their own static fields.
Try it yourself
- Write a generic method
Swap<T>(ref T a, ref T b)and test it with ints and strings. - Write
Filter<T>(IEnumerable<T>, Func<T, bool>)without using LINQ. - Create a generic
Stack<T>class backed by aList<T>withPush,PopandPeek. Decide whatPopshould do on an empty stack.
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