Skip to content

Generic Methods and Classes

The Course
•
30 min study

You've used List<int> and List<string> since the beginner course. Those aren't two classes: List<T> is one generic class, and T is a placeholder for a type that the user chooses. Today you'll write your own.

The problem without generics

Everything in C# can be stored as object, so you could write one container for all types. But the compiler no longer knows what's inside, so mistakes wait until the program runs.

object loses the type C#
var items = new List<object> { 1, "two" };
int first = (int)items[0];
Console.WriteLine(first);
int second = (int)items[1];
Console.WriteLine(second);
Check your prediction
Text
1
InvalidCastException

With List<int>, adding "two" is a compile error, and no cast is needed. Generics keep the check at compile time.

A generic method

<T> after the method's name declares the placeholder. Each caller gets the right type, and usually the compiler can infer it from the arguments.

One method, any type C#
Console.WriteLine(Last(new List<int> { 1, 2, 3 }));
Console.WriteLine(Last(new List<string> { "a", "b" }));
Console.WriteLine(LastOr(new List<int>(), -1));

static T Last<T>(List<T> items) => items[items.Count - 1];

static T LastOr<T>(List<T> items, T fallback)
{
    return items.Count == 0 ? fallback : items[items.Count - 1];
}
Check your prediction
Text
3
b
-1

Nothing is converted to object. The compiler treats Last with int and Last with string as separately checked uses, so int x = Last(words); won't compile.

A generic class

A class can take type parameters too, and methods inside it can use T freely. Here's a small stack, built by composition on a private list, so that only stack operations are exposed.

A stack of anything C#
var numbers = new Pile<int>();
numbers.Push(1);
numbers.Push(2);
Console.WriteLine(numbers.Pop());
Console.WriteLine(numbers.Count);

var words = new Pile<string>();
words.Push("only");
Console.WriteLine(words.Pop());
Console.WriteLine(words.Count);

class Pile<T>
{
    private readonly List<T> items = new();

    public int Count => items.Count;

    public void Push(T item)
    {
        items.Add(item);
    }

    public T Pop()
    {
        if (items.Count == 0)
        {
            throw new InvalidOperationException("The pile is empty");
        }
        T top = items[items.Count - 1];
        items.RemoveAt(items.Count - 1);
        return top;
    }
}
Check your prediction
Text
2
1
only
0

Several type parameters

A type can take more than one parameter, as Dictionary<TKey, TValue> does. Records work the same way, which makes small generic results and pairs very short to write.

A record with two type parameters C#
var pair = new Pair<string, int>("minutes", 25);
Console.WriteLine(pair);
Console.WriteLine(Swap(pair));

static Pair<B, A> Swap<A, B>(Pair<A, B> pair) => new Pair<B, A>(pair.Second, pair.First);

record Pair<TFirst, TSecond>(TFirst First, TSecond Second);
Check your prediction
Text
Pair { First = minutes, Second = 25 }
Pair { First = 25, Second = minutes }

Name a lone parameter T. When there are several, use descriptive names such as TKey.

Fix it: A type argument that doesn't match

Someone wrote the type argument out by hand. Run it and read the error.

A type argument that doesn't match C#
var words = new List<string> { "a", "b" };
Console.WriteLine(Last<int>(words));

static T Last<T>(List<T> items) => items[items.Count - 1];
Check your prediction
Text
error CS1503
cannot convert from 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<int>'

Last<int> asks for the version of Last whose T is int, which takes a List<int>. A List<string> isn't one, even though both are lists. Fix the call.

Fix it

Leave the type argument out, and let the compiler infer T from the argument:

C#
var words = new List<string> { "a", "b" };
Console.WriteLine(Last(words));

static T Last<T>(List<T> items) => items[items.Count - 1];
Text
b

Writing Last<string>(words) also works. Usually you don't write the type argument at all, and inference can't get it wrong. You need it only when there's no argument to infer from, as with new List<int>().

Your turn

Exercise

A bounded recent list

Write a generic class Recent<T> that remembers only the last capacity items added. It needs a constructor that takes the capacity, a method Add(T item), and a property Items that returns the items oldest first as IReadOnlyList<T>. A capacity below 1 should throw ArgumentOutOfRangeException.

Add 1, 2, 3 and 4 to a Recent<int> with capacity 3, then print the items joined with commas. Then add "a" to a Recent<string> with capacity 2 and print its count.

When it works, it prints:

Text
2,3,4
1
Your workspace C#
Console.WriteLine("Start here");
Hint 1: the idea

Hold a private List<T>. After adding, if it's over capacity, remove the item at the front.

Hint 2: a first step

Write the class with Add and Items and no limit, and check that it works with int. Then add the capacity.

Show one solution
C#
var numbers = new Recent<int>(3);
foreach (int number in new[] { 1, 2, 3, 4 })
{
    numbers.Add(number);
}
Console.WriteLine(string.Join(",", numbers.Items));

var words = new Recent<string>(2);
words.Add("a");
Console.WriteLine(words.Items.Count);

class Recent<T>
{
    private readonly List<T> items = new();
    private readonly int capacity;

    public Recent(int capacity)
    {
        ArgumentOutOfRangeException.ThrowIfLessThan(capacity, 1);
        this.capacity = capacity;
    }

    public IReadOnlyList<T> Items => items;

    public void Add(T item)
    {
        items.Add(item);
        if (items.Count > capacity)
        {
            items.RemoveAt(0);
        }
    }
}
Text
2,3,4
1

Adding first and then removing the oldest keeps Add simple: the list is never more than one over its limit, and only for a moment. Items is an IReadOnlyList<T>, so callers can read but not add around the limit. Checking capacity in the constructor means a Recent<T> can never exist in a state that makes no sense.

Was this article helpful?

Your response is saved on this device.