C# Generics
Generics let you write classes and methods that work with any type while staying fully type-safe. Instead of writing IntStack, StringStack and CustomerStack, you write one Stack<T>, where T is a type parameter filled in by whoever uses it. You have already used generics: List<string> and Dictionary<string, int> are generic types.
The problem generics solve
Without generics, a reusable container has to store object. That loses type safety — the compiler cannot stop you from mixing types — and forces casts everywhere:
object[] box = new object[2];
box[0] = 42;
box[1] = "oops"; // compiles fine
int n = (int)box[1]; // InvalidCastException at run timeWith generics, the mistake is caught at compile time and no casts are needed.
Generic methods
Add a type parameter in angle brackets after the method name. The compiler usually infers T from the arguments.
using System;
static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
static T[] Repeat<T>(T value, int count)
{
T[] result = new T[count];
for (int i = 0; i < count; i++) result[i] = value;
return result;
}
int x = 1, y = 2;
Swap(ref x, ref y); // T inferred as int
Console.WriteLine(quot;{x} {y}");
string s = "left", t = "right";
Swap<string>(ref s, ref t); // T given explicitly
Console.WriteLine(quot;{s} {t}");
Console.WriteLine(string.Join(",", Repeat("ab", 3)));
Console.WriteLine(string.Join(",", Repeat(7.5, 2)));2 1
right left
ab,ab,ab
7.5,7.5
Generic classes
A generic class declares its type parameters after the class name. Here is a simple fixed-size history buffer that works for any element type:
using System;
var recent = new History<string>(3);
recent.Add("home");
recent.Add("products");
recent.Add("cart");
recent.Add("checkout"); // oldest entry drops out
Console.WriteLine(string.Join(" > ", recent.Items()));
var temps = new History<double>(2);
temps.Add(20.5);
temps.Add(21.0);
Console.WriteLine(temps.Latest);
class History<T>
{
private readonly T[] buffer;
private int count;
private int next;
public History(int capacity) => buffer = new T[capacity];
public void Add(T item)
{
buffer[next] = item;
next = (next + 1) % buffer.Length;
if (count < buffer.Length) count++;
}
public T Latest => buffer[(next - 1 + buffer.Length) % buffer.Length];
public T[] Items()
{
T[] result = new T[count];
int start = (next - count + buffer.Length) % buffer.Length;
for (int i = 0; i < count; i++)
result[i] = buffer[(start + i) % buffer.Length];
return result;
}
}products > cart > checkout
21
History<string> and History<double> are two different, fully type-checked types: recent.Add(5) would not compile.
Constraints
Sometimes your generic code needs to do something with T — compare values, create new instances, call a method. A where clause constrains which types are allowed, and in return lets you use those capabilities:
using System;
static T Largest<T>(T[] items) where T : IComparable<T>
{
T best = items[0];
foreach (T item in items)
if (item.CompareTo(best) > 0) best = item;
return best;
}
Console.WriteLine(Largest(new[] { 3, 17, 8 }));
Console.WriteLine(Largest(new[] { "pear", "apple", "zucchini", "fig" }));
Console.WriteLine(Largest(new[] { 2.5, -1.0 }));17
zucchini
2.5
| Constraint | Meaning |
|---|---|
where T : class |
T must be a reference type |
where T : struct |
T must be a non-nullable value type |
where T : new() |
T must have a public parameterless constructor |
where T : SomeBase |
T must be or derive from SomeBase |
where T : ISomething |
T must implement the interface |
where T : notnull |
T must be a non-nullable type |
Multiple type parameters and default
A type can have several type parameters, like Dictionary<TKey, TValue>. The default keyword gives the default value of any T (0, false or null):
using System;
var pair = new Pair<string, int>("answer", 42);
Console.WriteLine(pair);
Console.WriteLine(FirstOrFallback(new int[0]));
Console.WriteLine(FirstOrFallback(new[] { "x", "y" }));
Console.WriteLine(FirstOrFallback(new string[0]) ?? "(null)");
static T FirstOrFallback<T>(T[] items) => items.Length > 0 ? items[0] : default;
class Pair<TFirst, TSecond>
{
public TFirst First { get; }
public TSecond Second { get; }
public Pair(TFirst first, TSecond second) { First = first; Second = second; }
public override string ToString() => quot;({First}, {Second})";
}(answer, 42)
0
x
(null)
Generics in the standard library
| Generic type | Purpose |
|---|---|
List<T> |
Resizable array |
Dictionary<TKey, TValue> |
Key/value lookup |
HashSet<T> |
Unique values |
Queue<T> / Stack<T> |
FIFO / LIFO collections |
Func<T, TResult> / Action<T> |
Delegates for lambdas |
Task<T> |
An asynchronous result |
Nullable<T> |
The type behind int? |
Tip: Name a single type parameter
T. With several, use descriptive names starting withT:TKey,TValue,TResult.
Test yourself
What is the main benefit of List<int> over a list of object?
- It uses less code to declare
- Type safety at compile time and no casting
- It can hold any type
- It is always sorted
Which constraint lets you call CompareTo on values of type T?
- where T : class
- where T : new()
- where T : IComparable<T>
- where T : struct
What is default(T) when T is int?
- null
- 0
- -1
- It does not compile