×

c# · level 3 · unit 1 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A tells C# what your type can do.

Inside a generic method, C# knows nothing about T, so it only lets you use what every object has, like Equals. To find the biggest item you must compare, and plain T has no CompareTo. Writing item.CompareTo(best) stops with CS1061.

A constraint fixes this. Write where T : IComparable<T> after the brackets, and only types that can compare themselves are allowed in. string, int and double all implement IComparable, so inside the method CompareTo is ready to use.

a.CompareTo(b) answers with a number: below zero when a comes first, zero when they match, above zero when a comes after. Check the sign, never the exact value.

using System;
using System.Collections.Generic;

Console.WriteLine(Biggest(new List<int> { 4, 19, 7 }));
Console.WriteLine(Biggest(new List<string> { "kiwi", "apple", "plum" }));
Console.WriteLine(Biggest(new List<double> { 2.5, 0.75 }));

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

Every built-in number type, including decimal for money (written 3.40m), implements IComparable<T>.