Skip to content

Generic Constraints

The Course
•
30 min study

Inside a generic method, T could be anything, so the compiler only lets you do what works on everything. Try to compare two T values and it refuses. A constraint, written with where, narrows T so that more operations become available.

Why a constraint is needed

Max needs to compare values, but an arbitrary T might not be comparable. Run this to see the error.

The compiler can't assume anything C#
Console.WriteLine(Max(1, 2));

static T Max<T>(T a, T b)
{
    return a > b ? a : b;
}
Check your prediction
Text
error CS0019
Operator '>' cannot be applied

Now state the requirement. where T : IComparable<T> means "only types that can compare themselves to their own kind". int, string and DateOnly all qualify.

A constraint makes it work C#
Console.WriteLine(Max(1, 2));
Console.WriteLine(Max("apple", "pear"));
Console.WriteLine(Max(new DateOnly(2026, 1, 2), new DateOnly(2025, 12, 31)));

static T Max<T>(T a, T b) where T : IComparable<T>
{
    return a.CompareTo(b) > 0 ? a : b;
}
Check your prediction
Text
2
pear
01/02/2026

Calling Max(new object(), new object()) is now a compile error at the call, where the mistake is.

Using your own interface

A constraint can name your own interface or base class. Then the generic code can call its members and still return the precise type. Newest below returns a Note when it's given notes, with no cast at the call.

Keep the exact type C#
var notes = new List<Note> { new("old", 1), new("new", 5) };
Note latest = Newest(notes);
Console.WriteLine(latest.Text);

static T Newest<T>(List<T> items) where T : IVersioned
{
    T best = items[0];
    foreach (T item in items)
    {
        if (item.Version > best.Version)
        {
            best = item;
        }
    }
    return best;
}

interface IVersioned
{
    int Version { get; }
}

record Note(string Text, int Version) : IVersioned;
Check your prediction
Text
new

The other common constraints

ConstraintMeans
where T : classT is a reference type
where T : structT is a value type such as int
where T : notnullT isn't a nullable type
where T : new()T has a public constructor with no parameters
where T : SomeBase, ISomethingSeveral requirements, separated by commas

new() lets generic code create objects. default gives the "empty" value of T: 0 for numbers, false for bool, and null for reference types. Because that value can be null, Empty below returns T?. On a T with no constraint, the ? only marks that a reference type may be null: for int, T? is still plain int, so Empty<int>() gives 0, not null.

new() and default C#
#nullable enable

var made = Make<Settings>();
Console.WriteLine(made.Theme);
Console.WriteLine(Empty<int>());
Console.WriteLine(Empty<bool>());
Console.WriteLine(Empty<string>() is null);

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

static T? Empty<T>() => default;

class Settings
{
    public string Theme { get; set; } = "light";
}
Check your prediction
Text
light
0
False
True

Don't over-generalize

A generic method is worth writing when two or more real uses exist, or when a library is meant to be general. If you only ever use Newest with notes, a plain method is easier to read. You'll meet advanced generics, including variance and generic math, in the Advanced course.

Fix it: new T() needs a promise

MakeTwo creates two fresh objects of any type. Run it and read the error.

new T() needs a promise C#
var pair = MakeTwo<List<int>>();
pair.First.Add(1);
Console.WriteLine(pair.First.Count);
Console.WriteLine(pair.Second.Count);

static (T First, T Second) MakeTwo<T>()
{
    return (new T(), new T());
}
Check your prediction
Text
error CS0304
Cannot create an instance of the variable type 'T' because it does not have the new() constraint

Not every type has a constructor without parameters (string doesn't, and neither does an interface), so the compiler can't assume new T() works. Fix MakeTwo with the constraint the error names.

Fix it

Add where T : new():

C#
var pair = MakeTwo<List<int>>();
pair.First.Add(1);
Console.WriteLine(pair.First.Count);
Console.WriteLine(pair.Second.Count);

static (T First, T Second) MakeTwo<T>() where T : new()
{
    return (new T(), new T());
}
Text
1
0

Now MakeTwo<string>() is the compile error, at the call, which is where the mistake would be. The two lists are separate objects, so adding to one leaves the other at 0.

Your turn

Exercise

Largest by a score

Define an interface IScored with an int Score property. Write Top<T>(List<T> items, int count), with a constraint, that returns a new list of the count highest scorers, highest first. It must not change the input, and asking for more than exist returns all of them. Use records Player(string Name, int Score) and Essay(string Title, int Score).

Print the name of each of the top two of Ana 5, Ben 9 and Cy 7, then the name of the first player in the original list, to show it kept its order, then the number of essays returned when you ask for 5 from a list of one.

When it works, it prints:

Text
Ben
Cy
Ana
1
Your workspace C#
Console.WriteLine("Start here");
Hint 1: the idea

Copy the list, sort the copy with a comparison that looks at Score, then keep at most count items.

Hint 2: a first step

Write the interface and the signature with its where clause, then create the copy with new List<T>(items). Sort accepts a lambda taking two items, and Math.Min protects the count.

Show one solution
C#
var players = new List<Player> { new("Ana", 5), new("Ben", 9), new("Cy", 7) };
foreach (Player player in Top(players, 2))
{
    Console.WriteLine(player.Name);
}
Console.WriteLine(players[0].Name);
Console.WriteLine(Top(new List<Essay> { new("Rain", 3) }, 5).Count);

static List<T> Top<T>(List<T> items, int count) where T : IScored
{
    var sorted = new List<T>(items);
    sorted.Sort((a, b) => b.Score.CompareTo(a.Score));
    return sorted.GetRange(0, Math.Min(count, sorted.Count));
}

interface IScored
{
    int Score { get; }
}

record Player(string Name, int Score) : IScored;

record Essay(string Title, int Score) : IScored;
Text
Ben
Cy
Ana
1

The constraint where T : IScored is what allows a.Score, and it still returns a List<T>, so the caller gets players back and not just scored things. Sorting a copy keeps the caller's list unchanged, which is what the players[0].Name line checks. Math.Min handles asking for more items than there are, as the essay list does.

The (a, b) => ... passed to Sort is a lambda, a small method written in place. Tomorrow starts with those. The third printed line confirms that the original list kept its order.

Was this article helpful?

Your response is saved on this device.