C# Generics
ExampleC#
using System;
using System.Collections.Generic;
class Box<T>
{
private T value;
public Box(T value) { this.value = value; }
public T Get() { return value; }
}
class Program
{
static T Largest<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) >= 0 ? a : b;
}
static void Main()
{
Console.WriteLine(Largest(3, 9));
Console.WriteLine(Largest("apple", "banana"));
Box<int> n = new Box<int>(42);
Box<string> s = new Box<string>("text");
Console.WriteLine(n.Get() + " " + s.Get());
List<double> prices = new List<double> { 4, 8 };
Console.WriteLine(prices.Count);
}
}Output
9 banana 42 text 2
where T : IComparable<T> is a constraint: it says the type must be comparable, which is what lets CompareTo be used.
Quick check
What does where T : IComparable<T> do?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.