The Problem Generics Solve
Imagine a class that stores an int. Now you need the same for string, then Customer. Copying the class each time is wasteful. Generics let you write it once with a placeholder type T.
A Generic Class
csharp
class Box<T>
{
public T Value { get; }
public Box(T value) => Value = value;
public override string ToString() => $"Box({Value})";
}
var number = new Box<int>(42);
var text = new Box<string>("hello");
Console.WriteLine(number); // Box(42)
Console.WriteLine(text.Value.ToUpper()); // type safe: Value is a string
Type safety: Box<int> can only hold int. The compiler refuses new Box<int>("x"), so mistakes are found before the program runs.
A Generic Method
csharp
void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
int x = 1, y = 2;
Swap(ref x, ref y); // T is inferred as int
string s1 = "A", s2 = "B";
Swap(ref s1, ref s2); // T is inferred as string
Constraints with where
Sometimes you need to promise the compiler something about T.
csharp
T Largest<T>(IEnumerable<T> items) where T : IComparable<T>
{
T best = items.First();
foreach (T item in items)
if (item.CompareTo(best) > 0) best = item;
return best;
}
Console.WriteLine(Largest(new[] { 3, 9, 4 })); // 9
Console.WriteLine(Largest(new[] { "pear", "apple" })); // pear
| Constraint | Meaning |
where T : class | T must be a reference type |
where T : struct | T must be a value type |
where T : new() | T must have a parameterless constructor |
where T : SomeInterface | T must implement the interface |
where T : notnull | T cannot be null |
A Practical Example: Generic Repository
csharp
interface IRepository<T> where T : class
{
void Add(T item);
IReadOnlyList<T> GetAll();
}
class InMemoryRepository<T> : IRepository<T> where T : class
{
private readonly List<T> items = [];
public void Add(T item) => items.Add(item);
public IReadOnlyList<T> GetAll() => items;
}
IRepository<string> names = new InMemoryRepository<string>();
names.Add("Ana");
Generic Types You Already Know
| Type | Meaning |
List<T> | A growing list of T |
Dictionary<TKey, TValue> | Key-value pairs |
Task<T> | An async operation that returns T |
IEnumerable<T> | A sequence of T |
C# 14: Extension Members
An extension adds members to an existing type without changing it. C# 14 adds an extension block that supports properties too (needs the .NET 10 SDK).
csharp
static class StringExtensions
{
extension(string text)
{
public bool IsBlank => string.IsNullOrWhiteSpace(text);
public string Shorten(int max) => text.Length <= max ? text : text[..max] + "...";
}
}
Console.WriteLine(" ".IsBlank); // True
Console.WriteLine("Hello World".Shorten(5)); // Hello...
Older style: Classic extension methods (static string Shorten(this string text, int max)) still work and are everywhere in existing code.
Conclusion
Generics give you type-safe, reusable code. Add constraints when you need guarantees about T, and learn the built-in generic collections next.
Quick Summary: Class<T> and Method<T> reuse code for any type. where T : ... adds rules.