Skip to content
AgileLogics
4 min read

Generics

Prerequisites: Custom exceptions

class Box<T> {
    private T _value = default!;

    public void Set(T value) => _value = value;
    public T Get() => _value;
}

var stringBox = new Box<string>();
stringBox.Set("Hello");
string value = stringBox.Get(); // no cast needed

var intBox = new Box<int>();
intBox.Set(42);

Unlike Java, C# generics work directly with primitive types like int (no boxing into a wrapper class needed) — one of a few genuine technical advantages C#'s generics have over Java's.

Practice

Write a generic method T FirstOf<T>(List<T> list) that returns the first element of any list.

Show solution
static T FirstOf<T>(List<T> list) => list[0];