Codiqo

Learn C# · lesson 56 of 61 · about 9 minutes

Generic Methods and Constraints

Write methods that work for any type, and say what the type must be able to do.

What you'll learn

  • Write a generic method with <T>
  • Let the compiler work out T from the arguments
  • Limit T with where T : IComparable<T>

The wards on the door

The lair's door is covered in wards that hold everything in bounds. Inside, a critical hit is never less than x1 or more than x2, the power of a hit stays between 10 and 20, and the hero can carry in at most 30 gold. That's the same job three times, once for a double and twice for an int: keep a value between a low and a high bound. A generic method, Clamp<T>, does it for any type that can be compared, and the hero reads Inside the wards: crit x1.5, power 15, gold 6.

Generic methods

A method can have its own type parameter, written after its name: static T Last<T>(List<T> items). When you call Last(words), the compiler sees a List<string> and works out that T is string.

static void Swap<T>(ref T a, ref T b) swaps any two variables of the same type.

Works for any type

int x = 1, y = 2;
Swap(ref x, ref y);
string a = "left", b = "right";
Swap(ref a, ref b);
Console.WriteLine($"{x} {y} {a} {b}");
Console.WriteLine(Middle(new List<string> { "a", "b", "c" }) + Middle(new List<int> { 4, 5, 6 }));

static void Swap<T>(ref T a, ref T b)
{
    (a, b) = (b, a);
}

static T Middle<T>(List<T> items) => items[items.Count / 2];

Output

2 1 right left
b5

Constraints

Inside a generic method, C# only lets you do things that work for every possible T. To compare items, add a constraint: where T : IComparable<T> means T must have CompareTo. ints, doubles and strings all do.

Biggest of any comparable type

Console.WriteLine(Biggest([3, 9, 4]));
Console.WriteLine(Biggest(["kiwi", "pear", "fig"]));

static T Biggest<T>(List<T> items) where T : IComparable<T>
{
    T best = items[0];
    foreach (T x in items)
        if (x.CompareTo(best) > 0) best = x;
    return best;
}

Output

9
pear

Why Clamp needs the constraint

Clamp compares the value with both bounds, so it calls CompareTo, and only types that promise CompareTo may be used: where T : IComparable<T>. double and int both keep that promise. You never write Clamp<double>: from Clamp(crit, 1.0, 2.0) the compiler sees doubles and works out T itself, and from Clamp(power, 10, 20) it sees ints. A negative CompareTo against the low bound means the value comes before it, so the low bound is given back; a positive one against the high bound gives the high bound; and anything in between comes back as it was.

Tip

a.CompareTo(b) is negative if a comes first, positive if b does, and 0 if they're equal.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.