C# Tutorial · Object-Oriented C# · Lesson 15 of 22

C# Generics

Generic classes and methods with type constraints.

Generic types and methods

Generics let you write type-safe code once for many types — List<T> and Dictionary<TKey, TValue> are generic:

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

var stack = new Stack<string>();
stack.Push("a");
stack.Push("b");
Console.WriteLine($"{stack.Pop()} {stack.Count}");
Console.WriteLine(Max(new[] { 3, 9, 4 }) + " " + Max(new[] { "pear", "apple" }));
var box = new Box<int>(42);
Console.WriteLine(box);

record Box<T>(T Value);

Output

b 1
9 pear
Box { Value = 42 }

Run this on your computer — see “Get Started” for setup.

Constraints

where T : ... restricts the type argument: class, struct, new(), a base class or an interface such as IComparable<T>.

Test yourself

Which clause adds a constraint to a type parameter?

  1. when
  2. where
  3. extends
  4. requires
Show answer

Answer: where