C# Generics: Type Safety Without Duplication
Learn how C# generics preserve types without duplication, from generic classes and methods to constraints, variance, and runtime tradeoffs.

When you write the same logic for multiple types, C# generics let you define that logic once and keep compile-time type information. Instead of casting from object or duplicating methods, a generic type parameter preserves the exact type at the call site. This article explains how C# generics work in practice, including constraints, runtime behavior, variance, and the tradeoffs that matter when you use them in production code.
The Core Problem Generics Solve
Without generics, you often end up with two options: duplicate a method for each type, or accept object and lose type safety. Duplication is hard to maintain; object requires casting and risks runtime exceptions. Generics provide a third path: a single definition that works with any type, while the compiler tracks the specific type used.
For example, a simple swap function:
public static void Swap<T>(ref T left, ref T right)
{
T temp = left;
left = right;
right = temp;
}The type argument can be supplied explicitly or inferred; either way, the compiler ensures both arguments match. No casting, no runtime type checks.
Generic Classes and Methods
Generic classes are the most common form. A generic collection like List<T> is a familiar example. You can define your own:
public class Repository<T>
{
private readonly List<T> _items = new();
public void Add(T item) => _items.Add(item);
public T Get(int index) => _items[index];
}Generic methods allow a method to have its own type parameter, independent of the class. This is useful for utility methods that work across many types:
public static T? FindOrDefault<T>(IEnumerable<T> source, Func<T, bool> predicate)
{
foreach (T item in source)
{
if (predicate(item))
{
return item;
}
}
return default;
}The type parameter is inferred from the arguments in most calls, so you rarely need to spell it out.
Type Constraints and Their Effect
Constraints tell the compiler what capabilities a type parameter must have. Without constraints, you can only use members of object. Constraints allow you to call methods, access properties, or enforce a base class or interface.
public static T Max<T>(T left, T right) where T : IComparable<T>
{
return left.CompareTo(right) > 0 ? left : right;
}Common constraints include where T : class, where T : struct, where T : new(), and where T : SomeBaseClass. Each constraint narrows the set of acceptable types, which lets you write more specific code. Over-constraining, however, reduces reusability. For instance, requiring new() prevents using types that don't have a parameterless constructor, even if you never create one.
How the Runtime Handles Generics
C# generics are reified: the runtime constructs a distinct closed type for each type argument. For reference type arguments, generated code can be shared, while value type arguments receive distinct native code. This means a List<int> is a different closed type from a List<string>. For value types, the JIT generates code that avoids boxing, so List<int> stores ints directly. This is a major performance advantage over non-generic collections like ArrayList.
The tradeoff is that generic code with many value type instantiations can increase JIT compilation time and memory usage. In most applications this is negligible, but high-throughput services with many generic types can see a measurable impact. Profiling is the only reliable way to decide whether it matters.
Variance in Interfaces and Delegates
Variance controls whether a value of one generic type can be converted to another generic type with a compatible type argument. Covariance (out T) allows an IEnumerable<string> to be assigned to IEnumerable<object>. Contravariance (in T) allows an Action<object> to be used where Action<string> is expected.
IEnumerable<string> strings = new List<string>();
IEnumerable<object> objects = strings; // covariance
Action<object> printObject = obj => Console.WriteLine(obj);
Action<string> printString = printObject; // contravarianceOnly interfaces and delegates can declare variance, and variance conversions apply only to reference types. Variance conversions are reference conversions, not boxing conversions, so value type arguments are not eligible.
Common Mistakes and Maintainability Concerns
One frequent mistake is ignoring constraints and using object inside a generic method, which defeats the purpose. Another is overusing generics for every abstraction, making code harder to read. Generics are a tool for preserving type information, not for hiding complexity.
When you add a generic type parameter, you increase the surface area of your API. Every consumer must either specify the type or rely on inference. If inference fails, the call site becomes noisy. Consider whether a non-generic interface or a base class would be simpler.
When to Avoid Generics
Generics are not always the right choice. If you need to store heterogeneous types in a single collection, a non-generic base type or object may be necessary. If the logic depends heavily on runtime type checks, a generic implementation often becomes a series of if (typeof(T) == ...) branches, which is a sign that the abstraction is wrong.
Performance is another consideration. While generics avoid boxing for value types, they also prevent certain optimizations. For example, a generic method that uses EqualityComparer<T>.Default can add a virtual call. In hot paths, a non-generic implementation specialized for a known type can be faster. Measure before optimizing.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# Dispose vs Destructor: Key Differences Explained
c# dispose vs destructor: Understand the difference between Dispose and destructors in C#, when each runs, and how to manage unmanaged resources correctly.
C# Variable Declaration: Syntax and Practical Usage
Learn how to declare variables in C# with explicit types, var, and nullable annotations, and understand how defaults, scope, and readability affect your choices.
C# Primary Constructors for Classes: Syntax and Usage
Learn how to use C# primary constructors for classes: syntax, initialization, dependency injection, and limitations with practical examples.
C# IComparer: Custom Sorting with IComparer<T>
Learn how to implement IComparer<T> in C# to define custom sort order for arrays and lists, handle nulls, and avoid common performance pitfalls.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.