Say you’re building the back office for a Phoenix landscaping company. You need in-memory stores for customers, work orders and invoices, and all three classes would be the same 30 lines with a new type name.
C# generics fix that: you write Repository<T> once, and the compiler checks every type you plug in. We’ll build that store on .NET 10, then add constraints.
Quick answer: put a type parameter in angle brackets (class Repository<T>, T Largest<T>(T[] items)) and limit it with where T : ....
Why Use Generics in C# Instead of object?
Before generics, a shared store kept everything as object, like the old ArrayList. That has two costs: wrong types only fail at run time, and every value type gets boxed. This program shows both:
#:property PublishAot=false
using System.Collections;
using System.Globalization;
CultureInfo.CurrentCulture = new("en-US");
var totals = new ArrayList { 1250, 980, 4310 }; // order totals
totals.Add("1,100"); // compiles fine
try { foreach (object o in totals) _ = (int)o; }
catch (InvalidCastException) { Console.WriteLine("ArrayList: InvalidCastException at run time"); }
long t0 = GC.GetAllocatedBytesForCurrentThread();
var boxed = new ArrayList();
for (int i = 0; i < 100_000; i++) boxed.Add(i); // boxes every int
long t1 = GC.GetAllocatedBytesForCurrentThread();
var typed = new List<int>();
for (int i = 0; i < 100_000; i++) typed.Add(i); // no boxing
long t2 = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine($"ArrayList: {t1 - t0:N0} bytes allocated");
Console.WriteLine($"List<int>: {t2 - t1:N0} bytes allocated");
Output:
ArrayList: InvalidCastException at run time
ArrayList: 4,497,536 bytes allocated
List<int>: 1,048,976 bytes allocated

Adding the string "1,100" compiled fine and blew up later. For 100,000 numbers, ArrayList allocated 4,497,536 bytes against 1,048,976 for List<int>, because each boxed int is its own heap object. My boxing and unboxing guide digs into why.
With a generic list, the bad line doesn’t compile at all, and the numbers stay inline in one array.
Generic Classes Example: Repository<T> and Result<T>
A generic class names its type parameter after the class name. Here’s the landscaping store: one Repository<T> serving customers, orders and invoices, all records:
#:property PublishAot=false
var customers = new Repository<Customer>();
customers.Add(new Customer(1, "Jenna Morales", "Phoenix, AZ"));
customers.Add(new Customer(2, "Tyler Brooks", "Austin, TX"));
var orders = new Repository<Order>();
orders.Add(new Order(501, 2, "TX"));
var invoices = new Repository<Invoice>();
invoices.Add(new Invoice(1001, 2, 1249.50m));
Console.WriteLine(customers.GetById(2));
Console.WriteLine(orders.GetById(501));
Console.WriteLine(invoices.GetById(1001));
Console.WriteLine($"Customers: {customers.Count}, missing: {customers.GetById(9)}");
interface IEntity { int Id { get; } }
record Customer(int Id, string Name, string City) : IEntity;
record Order(int Id, int CustomerId, string State) : IEntity;
record Invoice(int Id, int CustomerId, decimal Amount) : IEntity;
class Repository<T> where T : IEntity
{
private readonly Dictionary<int, T> _items = [];
public void Add(T item) => _items[item.Id] = item;
public T? GetById(int id) => _items.GetValueOrDefault(id);
public int Count => _items.Count;
}
Output:
Customer { Id = 2, Name = Tyler Brooks, City = Austin, TX }
Order { Id = 501, CustomerId = 2, State = TX }
Invoice { Id = 1001, CustomerId = 2, Amount = 1249.50 }
Customers: 2, missing:

Each new Repository<Customer>() is a separate closed type, and Add on it only accepts a Customer. The where T : IEntity line is what lets the class read item.Id; I explain it in the constraints section.
Asking for ID 9 printed nothing, because GetValueOrDefault returned null for a missing record. Inside it is a Dictionary
A Generic Result<T> Wrapper
The other generic class I add to almost every project is a small result type, so a method can return a value or a reason it failed:
#:property PublishAot=false
Result<decimal> quote = Result<decimal>.Ok(89.99m);
Result<decimal> denied = Result<decimal>.Fail("We don't ship to ZIP 99501 yet");
Console.WriteLine(quote);
Console.WriteLine(denied);
record Result<T>(bool Success, T? Value, string? Error)
{
public static Result<T> Ok(T value) => new(true, value, null);
public static Result<T> Fail(string error) => new(false, default, error);
}
Output:
Result { Success = True, Value = 89.99, Error = }
Result { Success = False, Value = 0, Error = We don't ship to ZIP 99501 yet }
Result<decimal> holds a price here, and the same record could hold an Invoice tomorrow. default fills Value on failure, which is 0 for a decimal.
Generic Methods Example with Type Inference
A method can have its own type parameter even inside a normal class. Usually you don’t write the type at the call: the compiler infers it from the arguments.
#:property PublishAot=false
int[] zips = [85004, 78701, 10001];
string[] names = ["Tyler", "Jenna", "Marcus"];
Console.WriteLine(Largest(zips)); // T inferred as int
Console.WriteLine(Largest(names)); // T inferred as string
Console.WriteLine(Largest<decimal>([19.99m, 249.50m, 5m]));
var (from, to) = ("Phoenix", "Denver");
Swap(ref from, ref to);
Console.WriteLine($"{from} -> {to}");
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;
}
static void Swap<T>(ref T x, ref T y) => (x, y) = (y, x);
Output:
85004
Tyler
249.50
Denver -> Phoenix

Largest(zips) became Largest<int> on its own. I passed <decimal> on the third call, which is the long form you need when the arguments don’t pin the type down.
LINQ is built from generic methods just like this one, which is why Where and Select work on any sequence.
Generics with Multiple Type Parameters (TKey, TValue)
Separate the parameters with commas and give each a name that says what it is. Microsoft’s convention is a T prefix: TKey, TValue, TIn, TOut.
#:property PublishAot=false
var taxRates = new Lookup<string, decimal>();
taxRates.Set("AZ", 0.056m);
taxRates.Set("TX", 0.0625m);
Console.WriteLine($"TX rate: {taxRates.Get("TX")}");
Console.WriteLine(Map<int, string>(85004, zip => $"ZIP {zip}"));
Console.WriteLine(Map(3, n => n * 19.99m)); // TIn int, TOut decimal
static TOut Map<TIn, TOut>(TIn input, Func<TIn, TOut> convert) => convert(input);
class Lookup<TKey, TValue> where TKey : notnull
{
private readonly Dictionary<TKey, TValue> _map = [];
public void Set(TKey key, TValue value) => _map[key] = value;
public TValue Get(TKey key) => _map[key];
}
Output:
TX rate: 0.0625
ZIP 85004
59.97
Each parameter can have its own constraint, so TKey is notnull while TValue stays open. Func<TIn, TOut> is a generic delegate; my C# delegates tutorial covers Func and Action.
C# Generics Constraints: Every where Clause
Without a constraint, the compiler only lets you use what every type has: the members of object. A constraint promises more, and the compiler rejects type arguments that break the promise.
| Constraint | Type argument must be | Since |
|---|---|---|
where T : class | A reference type (non-nullable in a nullable context) | C# 2 |
where T : class? | A reference type, nullable or not | C# 8 |
where T : struct | A non-nullable value type | C# 2 |
where T : notnull | A non-nullable value or reference type (warning only) | C# 8 |
where T : unmanaged | A struct with no reference fields (int, double, custom structs) | C# 7.3 |
where T : new() | Has a public parameterless constructor; must be last | C# 2 |
where T : Customer | That base class or a class derived from it | C# 2 |
where T : IEntity | Implements that interface (several allowed) | C# 2 |
where T : U | The type supplied for U, or one derived from it | C# 2 |
where T : allows ref struct | May be a ref struct such as Span | C# 13 |
You can combine them: where T : Customer, IComparable<T>, new(). The order is fixed: class/struct/notnull/unmanaged first, then a base class or interfaces, then new(), then allows ref struct.
What Happens When You Break a Constraint
I broke six constraints in one file to collect the real compiler messages. In the screenshot, I piped the run through findstr so only the diagnostic lines show:
#:property PublishAot=false
#nullable enable
var a = new Cache<int>(); // where T : class
var b = new Counter<string>(); // where T : struct
var c = Factory.Create<Invoice>(); // where T : new()
var d = new Buffer<string>(); // where T : unmanaged
var e = new Repository<string>(); // where T : IEntity
var f = new Lookup<string?>(); // where T : notnull
interface IEntity { int Id { get; } }
record Invoice(int Id, decimal Amount) : IEntity;
class Cache<T> where T : class { }
class Counter<T> where T : struct { }
class Buffer<T> where T : unmanaged { }
class Repository<T> where T : IEntity { }
class Lookup<T> where T : notnull { }
static class Factory { public static T Create<T>() where T : new() => new T(); }
Build output:
ConstraintErrors.cs(4,19): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Cache<T>'
ConstraintErrors.cs(5,21): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Counter<T>'
ConstraintErrors.cs(6,17): error CS0310: 'Invoice' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Factory.Create<T>()'
ConstraintErrors.cs(7,20): error CS8377: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Buffer<T>'
ConstraintErrors.cs(8,24): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Repository<T>'. There is no implicit reference conversion from 'string' to 'IEntity'.
ConstraintErrors.cs(9,20): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'Lookup<T>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint.

The ones you’ll search for most are CS0452 (needs a reference type), CS0453 (needs a non-nullable value type) and CS0310 (needs a public parameterless constructor). The notnull line produced warning CS8714, not an error.
Note: Invoice failed new() because a positional record only has the constructor with parameters. Add a parameterless constructor or drop the constraint.
allows ref struct in C# 13
allows ref struct is the opposite of a constraint: it widens what T may be, so a Span<int> can be the type argument.
#:property PublishAot=false
Span<int> zips = [85004, 78701, 10001];
Console.WriteLine(Describe(zips));
Console.WriteLine(Describe(42));
static string Describe<T>(T value) where T : allows ref struct
=> typeof(T).Name;
Output:
Span`1
Int32
Remove the clause and the same call stops compiling:
#:property PublishAot=false
Span<int> zips = [85004, 78701, 10001];
Console.WriteLine(Describe(zips));
static string Describe<T>(T value) => typeof(T).Name;
Build output:
NoAllowsRefStruct.cs(4,19): error CS9244: The type 'Span<int>' may not be a ref struct or a type parameter allowing ref structs in order to use it as parameter 'T' in the generic type or method 'Describe<T>(T)'
In exchange, the method can’t box value or store it in a field, because a ref struct has to stay on the stack.
Generic Interfaces: IRepository<T> and IComparable<T>
Interfaces take type parameters too. I split the store into an IRepository<T> contract and an implementation, and let the Invoice record sort itself through IComparable<Invoice>:
#:property PublishAot=false
IRepository<Invoice> repo = new MemoryRepository<Invoice>();
repo.Add(new Invoice(1001, 1249.50m));
repo.Add(new Invoice(1002, 89.99m));
repo.Add(new Invoice(1003, 640.00m));
List<Invoice> sorted = [.. repo.All()];
sorted.Sort(); // uses IComparable<Invoice>
Console.WriteLine(string.Join(", ", sorted.Select(i => i.Id)));
interface IRepository<T> { void Add(T item); IEnumerable<T> All(); }
class MemoryRepository<T> : IRepository<T>
{
private readonly List<T> _items = [];
public void Add(T item) => _items.Add(item);
public IEnumerable<T> All() => _items;
}
record Invoice(int Id, decimal Amount) : IComparable<Invoice>
{
public int CompareTo(Invoice? other) =>
other is null ? 1 : Amount.CompareTo(other.Amount);
}
Output:
1002, 1003, 1001
List<T>.Sort() called CompareTo and put the invoices in amount order: 1002 ($89.99), 1003, then 1001. The C# interfaces guide covers default members and explicit implementation.
In ASP.NET Core, you can register the open type once, AddScoped(typeof(IRepository<>), typeof(MemoryRepository<>)), and the container closes it per request. Picking the lifetime is in my DI lifetimes guide.
How Do You Restrict C# Generics to Numeric Types?
Use where T : INumber<T> from System.Numerics. It arrived in .NET 7 with C# 11 static abstract interface members, so T.Zero, + and / work on T:
#:property PublishAot=false
using System.Numerics;
int[] units = [12, 30, 8];
decimal[] sales = [1249.50m, 89.99m, 640.00m];
double[] miles = [12.5, 3.25, 40.25];
Console.WriteLine($"Units: {Sum(units)}");
Console.WriteLine($"Sales: {Sum(sales)}");
Console.WriteLine($"Miles: {Sum(miles)}");
Console.WriteLine($"Average sale: {Average(sales):F2}");
static T Sum<T>(T[] values) where T : INumber<T>
{
T total = T.Zero;
foreach (T v in values) total += v;
return total;
}
static T Average<T>(T[] values) where T : INumber<T>
=> Sum(values) / T.CreateChecked(values.Length);
Output:
Units: 50
Sales: 1979.49
Miles: 56
Average sale: 659.83

The same method summed 50 units, $1979.49 in sales and 56 miles. T.CreateChecked(values.Length) turns the int count into a T and throws if it doesn’t fit.
Covariance and Contravariance in C# Generics (out T, in T)
Variance answers one question: can a generic of Customer stand in for a generic of Person? Only interfaces and delegates can say yes, through out and in:
#:property PublishAot=false
IEnumerable<Customer> customers = [new("Jenna Morales"), new("Tyler Brooks")];
IEnumerable<Person> people = customers; // covariance (out T)
Console.WriteLine($"People: {people.Count()}");
Action<Person> greet = p => Console.WriteLine($"Hi, {p.Name}");
Action<Customer> greetCustomer = greet; // contravariance (in T)
greetCustomer(new Customer("Marcus Reed"));
object names = new List<string> { "AZ", "TX" };
object counts = new List<int> { 12, 30 };
Console.WriteLine($"List<string> as IEnumerable<object>: {names is IEnumerable<object>}");
Console.WriteLine($"List<int> as IEnumerable<object>: {counts is IEnumerable<object>}");
record Person(string Name);
record Customer(string Name) : Person(Name);
Output:
People: 2
Hi, Marcus Reed
List<string> as IEnumerable<object>: True
List<int> as IEnumerable<object>: False
IEnumerable<out T> is covariant and Action<in T> is contravariant, so both assignments compile. List<T> is a class, so it’s invariant: List<Person> list = new List<Customer>() doesn’t compile.
The last line printed False: variance only works for reference types, so List<int> is not an IEnumerable<object>.
default(T) and typeof: Open vs Closed Generic Types
default(T) gives you the zero value of whatever T is, and typeof(List<>) gives the open type with no argument filled in:
#:property PublishAot=false
Console.WriteLine($"int: {Show<int>()}, decimal: {Show<decimal>()}");
Console.WriteLine($"bool: {Show<bool>()}, string: {Show<string>()}");
Type open = typeof(List<>);
Type closed = typeof(List<Customer>);
Console.WriteLine($"{open.Name} open: {open.IsGenericTypeDefinition}");
Console.WriteLine($"{closed.Name} open: {closed.IsGenericTypeDefinition}");
Console.WriteLine($"Argument: {closed.GetGenericArguments()[0].Name}");
Type built = open.MakeGenericType(typeof(Invoice));
Console.WriteLine($"Same as List<Invoice>: {built == typeof(List<Invoice>)}");
static string Show<T>() => default(T)?.ToString() ?? "null";
record Customer(string Name);
record Invoice(int Id);
Output:
int: 0, decimal: 0
bool: False, string: null
List`1 open: True
List`1 open: False
Argument: Customer
Same as List<Invoice>: True
default is 0 for numbers, False for bool and null for reference types. Both list types are named List`1, the backtick count of type parameters. MakeGenericType closes an open type at run time.
Generic Collections in C#
You’ll use generics mostly through the built-in collections in System.Collections.Generic. I won’t repeat them here; they have their own guides:
List<T>for ordered items: List in C#Dictionary<TKey, TValue>for lookups by key (the one insideRepository<T>)HashSet<T>,Queue<T>andStack<T>for uniqueness, FIFO and LIFOIEnumerable<T>as the parameter type when a method only reads
Common C# Generics Mistakes and How to Fix Them
Two bugs I’ve shipped myself. Same Phoenix strings and records, run on .NET 10:
#:property PublishAot=false
using System.Text;
string s1 = "Phoenix";
string s2 = new StringBuilder("Phoenix").ToString();
Console.WriteLine($"s1 == s2: {s1 == s2}");
Console.WriteLine($"SameRef(s1, s2): {SameRef(s1, s2)}");
Console.WriteLine($"SameValue(s1, s2): {SameValue(s1, s2)}");
Counter<Customer>.Count += 2;
Counter<Invoice>.Count += 1;
Console.WriteLine($"Customer: {Counter<Customer>.Count}, Invoice: {Counter<Invoice>.Count}");
static bool SameRef<T>(T a, T b) where T : class => a == b;
static bool SameValue<T>(T a, T b) => EqualityComparer<T>.Default.Equals(a, b);
class Counter<T> { public static int Count; }
record Customer(string Name);
record Invoice(int Id);
Output:
s1 == s2: True
SameRef(s1, s2): False
SameValue(s1, s2): True
Customer: 2, Invoice: 1

| Mistake | What happens | Fix |
|---|---|---|
a == b with where T : class | Reference comparison, False for equal strings | EqualityComparer<T>.Default.Equals(a, b) |
Static field in Counter<T> | One copy per closed type (2 and 1 above) | Move shared state to a non-generic class |
new T() without a constraint | Compile error | Add where T : new() last |
T? with no constraint | default (0) for value types, not null | Add where T : struct or class |
If a type parameter only ever gets one argument, I delete it. An abstract base class or plain interface is often the simpler choice.
When Should You Use Generics in C#?
My rule: reach for generics when the same logic runs on different types and you’d otherwise cast or copy code.
- Same algorithm, different element type: a generic method (Largest, Sum).
- Same container or wrapper, different payload: a generic class (Repository<T>, Result<T>).
- The code needs a member of T: add the narrowest constraint that gives it to you.
- You want to add a method to every
IEnumerable<T>: a generic extension, now with C# 14 extension members.
These pair well with generics:
- Nullable reference types in C#
- Collection expressions in C#
- Unit testing C# code with xUnit
- Learn C# step by step
Frequently Asked Questions
What are generics in C#?
Generics let a class, interface, method or delegate take a type as a parameter, like List<T>. You write the code once, and the compiler checks types for each use without casts or boxing.
What is the difference between generics and object in C#?
An object parameter accepts anything and needs casts, so mistakes show up at run time and value types get boxed. A generic parameter keeps the real type, so mistakes fail at compile time.
How do I restrict a C# generic to numeric types?
Use where T : INumber<T> from System.Numerics (.NET 7 and later). It allows +, -, T.Zero and comparisons on int, decimal, double and the other built-in numbers.
What does where T : new() mean?
It requires a public parameterless constructor, so the code can call new T(). It must be the last constraint. Microsoft’s constraints on type parameters page lists every rule.
Can a generic class have more than one type parameter?
Yes. Separate them with commas, like Dictionary<TKey, TValue>, and give each its own where clause if it needs one.
Bijay Kumar is a renowned software engineer, accomplished author, and distinguished Microsoft Most Valuable Professional (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. Read more…