Generics and constraints

A generic method

A generic method takes a type as a parameter: the caller writes Max<int>(...) or lets the compiler infer it from the arguments, and one body serves every type. Without a constraint the body knows nothing about T beyond what object offers, so a constraint is what makes CompareTo callable:

Console.WriteLine(Max(3, 9, 2)); Console.WriteLine(Max("a", "c", "b")); Console.WriteLine(Max(1.5, 0.5, 2.5)); static T Max<T>(T first, T second, T third) where T : IComparable<T> { var max = first; if (second.CompareTo(max) > 0) { max = second; } if (third.CompareTo(max) > 0) { max = third; } return max; }

dotnet run

9
c
2.5

The three calls made three different closed methods, one per type argument, and each of them was compiled against the real type: no boxing, no cast, no object. That is why a generic collection of int stores integers and not boxed objects, and the lesson on boxing measures the difference.

A generic class and a constraint

A class takes type parameters the same way. The constraint where T : class allows the compiler to use null for a missing item, which a value type could not hold:

var shelf = new Shelf<Book>(); shelf.Add(new Book("Dune")); shelf.Add(new Book("Solaris")); Console.WriteLine(shelf.Get(0).Title); Console.WriteLine($"count {shelf.Count}"); Console.WriteLine($"found {shelf.Find(b => b.Title.StartsWith("S"))?.Title ?? "none"}"); Console.WriteLine($"missing {shelf.Find(b => b.Title.StartsWith("X"))?.Title ?? "none"}"); class Book(string title) { public string Title => title; } class Shelf<T> where T : class { private readonly List<T> items = new(); public int Count => items.Count; public void Add(T item) => items.Add(item); public T Get(int index) => items[index]; public T? Find(Predicate<T> match) => items.Find(match); }

dotnet run

Dune
count 2
found Solaris
missing none

Find returns T? and gives null when nothing matched, which the ?. and ?? of the print turn into none. Without the class constraint the compiler would refuse T? for a type that might be a struct.

new() and default(T)

Two more constraints describe what a type parameter can do: new() promises a public parameterless constructor, and default(T) gives the zero value of whatever T turns out to be.

var list = Create<List<int>>(); Console.WriteLine($"list count {list.Count}"); Console.WriteLine($"default int {default(int)} default string [{default(string) ?? "null"}]"); Console.WriteLine($"created {list.GetType().Name}"); static T Create<T>() where T : new() => new T();

dotnet run

list count 0
default int 0 default string [null]
created List`1

default(int) is 0 and default(string) is null, so inside a generic method default(T) may be either; a nullable reference type or Nullable<T> is the way to say "no value" for both. The backtick in List`1 is how the runtime names a generic type, and new() is the only way to construct a T the compiler knows nothing else about.

A violated constraint

The compiler checks a constraint at every call site, so a method that requires a reference type refuses an int:

Console.WriteLine(First(new[] { 1, 2 })); static T First<T>(T[] items) where T : class { return items[0]; }

dotnet build

Program.cs(1,19): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'First<T>(T[])'

Build FAILED.

Program.cs(1,19): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'First<T>(T[])'
0 Warning(s)
1 Error(s)

Time Elapsed 00:00:07.51

The message names the type argument, the constraint and the method, which is the whole story. The fix is to relax the constraint or to use a type that satisfies it: the method uses nothing of class here, so removing the constraint is the honest change.

Exercises

  1. Write Min<T> next to Max and call it with the three types.
  2. Add a where T : IComparable<T> constraint to Shelf and a method that returns the smallest item.
  3. Call Create<int>() and read the error, then explain what new() requires.
  4. Make Shelf take two type parameters, a key and a value, and keep the items in a Dictionary<TKey, TValue>.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a generic type parameter cost at run time for a value type?

    Answer

    Nothing: the method is compiled once per type argument

    The runtime specialises the code for a value type, so no box is needed.

  2. Why is the constraint where T : IComparable<T> needed for Max?

    Answer

    So the compiler knows CompareTo exists on T

    Without a constraint the body only has the members of object.

  3. What does this program print? Console.WriteLine(Max(2, 7)); static T Max<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b) > 0 ? a : b;

    Answer

    7

    The comparison picks the larger of the two arguments.

  4. What does default(T) give for a reference type?

    Answer

    null

    A reference type has no value, so default is null; for a struct it is the zeroed value.

  5. What does where T : new() require?

    Answer

    A public parameterless constructor

    new T() calls the parameterless constructor, so the constraint guarantees one exists.

  6. What does this program print? Console.WriteLine($"int {default(int)} str [{default(string) ?? "null"}]");

    Answer

    int 0 str [null]

    The zero of int prints as 0, and a null string prints as the text of the ?? fallback.

  7. Which error reports a type argument that breaks a class constraint?

    Answer

    CS0452

    CS0452 says the type must be a reference type for that parameter.

  8. What does where T : class allow in the body that where T : struct does not?

    Answer

    Comparing T with null and using T?

    Only a reference type can be null, so T? and null checks need the class constraint.

  9. What does this program print? Console.WriteLine(Count(new List<string> { "a", "b" })); static int Count<T>(IEnumerable<T> items) => items.Count();

    Answer

    2

    Count() on IEnumerable<T> needs no constraint, so the call works for any T.

  10. Which member can a generic method call on an unconstrained T?

    Answer

    The members of object, such as ToString and GetType

    Unconstrained T is object as far as the compiler is concerned.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev