Generics (C#)

Generics let you write classes and methods that work with any type, using a type placeholder in angle brackets like <T>. They give you reusable, type-safe code without sacrificing type checking.

C#

List<T> and Dictionary<TKey, TValue> are the most common generic types. The T is filled in when you use the type — List<int> stores integers, List<string> stores strings — and the compiler enforces it.

You can write your own generic methods and classes, and add constraints (such as where T : class) to require the type argument to have certain capabilities.

Syntax

class Box<T> { public T Value; }

Examples

C#

class Box<T>
{
    public T Value;
}

var intBox = new Box<int> { Value = 7 };
var strBox = new Box<string> { Value = "hi" };
Console.WriteLine($"{intBox.Value} {strBox.Value}");

Output:

7 hi

Learn it in a lesson

See also

Back to the Dictionary