0Pricing
C# Academy · Lesson

where Constraints

Constrain type parameters.

Why Constraints Exist

By default a type parameter T is treated almost like object, so the compiler allows very few operations on it. Constraints, written with where, tell the compiler more about T.

With that knowledge you can call methods, construct instances, or compare values safely.

void Show<T>(T value) where T : IFormattable
{
    // now ToString(format, provider) is available
}

Interface Constraints

An interface constraint requires T to implement a given interface. The body can then call that interface's members.

Below, where T : IComparable<T> guarantees a CompareTo method exists.

T Max<T>(T a, T b) where T : IComparable<T>
    => a.CompareTo(b) >= 0 ? a : b;

All lessons in this course

  1. Generic Methods
  2. Generic Classes
  3. where Constraints
  4. Generic Interfaces
← Back to C# Academy