0Pricing
C# Academy · Lesson

where Constraints

Constrain type parameters.

where Constraints is a free C# Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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;

Base Class Constraints

You can require T to derive from a specific base class. Then members of that base type are usable inside the generic code.

This is common in frameworks where all entities share a base type.

class Animal { public string Name = ""; }

string NameOf<T>(T a) where T : Animal => a.Name;

The class Constraint

where T : class requires T to be a reference type. This permits null assignment and reference equality checks.

It is typical for repositories, caches, and anything that stores nullable references.

T? FindOrNull<T>(bool found, T value) where T : class
    => found ? value : null;

The struct Constraint

where T : struct requires T to be a non-nullable value type. This lets you treat T as a value type and use T? as a nullable value type.

It is used by helpers that work only with numbers, enums, or small structs.

T? AsNullable<T>(T value) where T : struct
    => value;

The new() Constraint

The new() constraint requires that T has a public parameterless constructor. The body may then write new T().

Factories and object pools rely on this to create instances generically.

using System;

class Program
{
    static T Make<T>() where T : new() => new T();

    static void Main()
    {
        var list = Make<System.Collections.Generic.List<int>>();
        Console.WriteLine(list.Count);
    }
}

Combining Constraints

You can apply several constraints to one parameter. The ordering rules require class or struct first, then base class, then interfaces, then new() last.

The constraints are listed after a single where, separated by commas.

T Build<T>() where T : class, IComparable<T>, new()
    => new T();

Multiple where Clauses

When a method or class has several type parameters, each gets its own where clause. They are written one after another.

This keeps the constraints for each parameter clearly separated.

TResult Convert<TInput, TResult>(TInput x)
    where TInput : class
    where TResult : new()
    => new TResult();

A Runnable Constraint Example

This complete program uses an IComparable<T> constraint to find the larger of two values, working for both ints and strings.

The constraint is what makes CompareTo legal inside the method.

using System;

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

    static void Main()
    {
        Console.WriteLine(Max(3, 9));
        Console.WriteLine(Max("apple", "pear"));
    }
}

The notnull and unmanaged Constraints

Newer C# adds more constraints. where T : notnull forbids nullable types, useful for dictionary keys. where T : unmanaged restricts T to blittable value types for low-level code.

These tighten safety in specialized scenarios.

void Use<T>(T key) where T : notnull { }

unsafe void Raw<T>(T v) where T : unmanaged { }

Constraints Enable, Not Restrict, Power

Although they look like restrictions, constraints actually unlock capabilities. Without a constraint you can barely touch T; with one you gain its members.

Choose the minimal constraint that lets your algorithm work, keeping the type parameter as flexible as possible.

// No constraint: only object members available
string Name<T>(T x) => x.ToString();

Quick Check

Test your understanding of where constraints.

Recap

The where clause constrains type parameters: interface, base class, class, struct, new(), notnull, and unmanaged. Each constraint unlocks specific operations on T.

Order them correctly, use one clause per parameter, and pick the minimal constraint your algorithm needs.

Frequently asked questions

Is the “where Constraints” lesson free?

Yes — the full text of “where Constraints” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “where Constraints”?

Constrain type parameters. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “where Constraints” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

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