c# · level 3 · unit 1 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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>.
guess first
Keep values inside a range. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
Console.WriteLine(Clamp(15, 0, 10));
Console.WriteLine(Clamp(-3, 0, 10));
Console.WriteLine(Clamp("m", "a", "f"));
T Clamp<T>(T value, T low, T high) where T : IComparable<T>
{
if (value.CompareTo(low) < 0)
{
return low;
}
if (value.CompareTo(high) > 0)
{
return high;
}
return value;
}
your turn
Your turn. Find the smallest of anything.
Add a constraint in the gap on line 9 so CompareTo works. Then fill line 5 with three town names of your own, in quotes.
output
press run to see what happens
fix it
The bargain finder picks the dearest price. Can you fix it?
output
press run to see what happens
- The code runs, but it shows 3.40. Look at the test inside the loop.
CompareTois above zero whenitemcomes afterbest, so this keeps the biggest.- Change
> 0to< 0on line 12, then run.
nailed it
your generic code can compare now. :D
- A constraint says what
Tmust be able to do. where T : IComparable<T>unlocksCompareTo.- Check the sign of
CompareTo, never the exact number.
new words in your collection
- constraint
This lesson isn’t saved. A free account remembers every lesson you finish.