Chapter 7: Generics
Bruce: “Robin, why do you have so many custom collection classes? Things like
EmployeeList,CustomerList,VendorList… do they have special behavior?”Robin: “Not really. Back when we used
ArrayListto store these objects, every read needed a bunch of casts. To avoid manual casting, I made separate list classes for employees, customers, and vendors. It took time up front, but the payoff was compile-time type safety, no manual casting, and cleaner code.”Bruce: “Fair. But… have you considered generics?”
This chapter explores C# generics. Generics are an important abstraction in modern C#, letting you write type-safe, reusable code while avoiding unnecessary performance costs and runtime cast errors. They also align well with the DRY principle (Don’t Repeat Yourself).
7.1 Why do we need generics?
The essence of generics is parameterized types: abstracting the type itself into a parameter so that the same logic can safely apply to diverse data types without duplicating classes or relying on casting from object.
The dilemma without generics: type safety and boxing costs
Before generics, general-purpose collections stored elements as object (such as ArrayList in early .NET):
This approach suffered from two major flaws:
- Loss of compile-time type safety: Any type can be placed into the collection; type mismatches may remain undetected until an invalid cast occurs at runtime.
- Performance and memory overhead: When storing value types like
int, every insert requires boxing onto the heap, and every read requires unboxing, creating significant GC pressure and CPU overhead with large data sets.
To achieve type safety, early developers had to manually duplicate dedicated collection classes for each type (like IntList, StringList), violating the DRY (Don’t Repeat Yourself) principle and dramatically raising maintenance costs.
The generic solution: compile-time contracts and type specialization
Generics resolve this dilemma elegantly. By placing angle brackets <T> after the type name, the decision of which type to use is delegated to the caller:
With generic collections: - Type safety: The compiler rejects incompatible element types, and retrieving an element requires no manual cast. - Reduced boxing overhead: The backing array of List<int> stores int values directly, without boxing each element as object. Section 7.7 discusses runtime implementation. - Code reuse: A single List<T> satisfies list requirements for all types.
Source code: DemoWhyGenerics
7.2 Generics in depth
The List<int> and List<string> examples use the same list definition; only the element type differs. When designing your own generic type, use a type parameter for the part that varies with the caller’s needs.
Generics, type parameters, constructed types
Generics can be used with classes, interfaces, delegates, and methods. Here is the basic syntax for a generic class:
The angle brackets <> contain type parameters (T1, T2, …, Tn), which represent the variable parts. You can have one or many.
By convention, a single type parameter is named T (for example, List<T>). For multiple parameters, use descriptive names.
The generic collection Dictionary<TKey, TValue> is a good example: you can immediately see that each entry contains a key and a value, and the actual types for those two parts are supplied when you use the collection.
Note that ClassName<T> is not a concrete runtime type. It is a type blueprint with slots for type arguments, so you cannot instantiate this open type directly. Calling it a “template” is only a helpful metaphor; .NET generics and C++ templates use different implementation mechanisms, which Section 7.7 discusses in more detail. For now, let’s focus on how an open type becomes a type you can actually use.
Supplying type arguments to a generic type definition creates a constructed type, such as Dictionary<int, string> or Dictionary<string, Employee>. A type with no remaining type parameters is closed; a type that still contains type parameters is open. For example, Dictionary<string, T> is both constructed and open. At runtime, substituting concrete arguments produces closed types.
Generics are templates for types
Think of generics as templates for types: List<T> is the common definition, and supplying int or string produces different constructed types. This analogy does not imply that the runtime duplicates machine code for every type.

Within a generic class, you can use its type parameter to construct another generic type:
When you create a Repository<int> object, _items is a List<int>.
Custom generic classes
Suppose we want our own list class, MyGenericList<T>, so that we can add application-specific operations later. We use the existing List<T> for storage instead of reimplementing capacity management, keeping the focus on how to define a generic class:
public class MyGenericList<T>
{
private readonly List<T> _elements;
public MyGenericList(int capacity = 0)
{
_elements = new List<T>(capacity);
}
public int Count => _elements.Count;
public void Add(T item) => _elements.Add(item);
public T this[int index]
{
get => _elements[index];
set => _elements[index] = value;
}
}The field, Add method, and indexer all use the same type parameter T. With int as T, Add takes an int and the indexer returns an int, without casting.
Both lists share the same definition but accept their own element types. In practice, if you do not need extra behavior, use List<T> directly rather than wrapping it.
Constructors and finalizers
Notice the constructor of MyGenericList<T> above: its name is MyGenericList, without repeating <T>. Inside it, you can use the class type parameter, for example in new List<T>(capacity) or new T[capacity].
Finalizer names follow the same naming rule, but whether a finalizer is necessary depends on resource ownership, not whether the class is generic (see Chapter 5).
Default values
To return the default value of a type from a generic method, use default(T). Since C# 7.1, you can shorten it to default when the target type is known. For example, this method returns the default value when an index is missing:
The default for int is 0, for bool it is false, and for reference types it is null. A value type’s default value is not necessarily valid business data, nor is it the same as calling a custom parameterless constructor.
Recall int? and string? from Chapter 3. T here is not constrained to value types, so T? does not always mean Nullable<T>. With NRT enabled, distinguish these cases:
| Declaration of T | Type argument | Meaning of T? |
|---|---|---|
| Unconstrained | int | int |
| Unconstrained | string | string? |
| where T : struct | int | int? (Nullable<int>) |
| where T : class | string | string? |
Calling GetValueOrDefault on MyGenericList<int> gives the same result for a missing index and an element that is actually 0. If the caller needs to distinguish success from failure, use the Try pattern from Chapter 5:
[MaybeNullWhen(false)] indicates that the output may be null when the method returns false, even if T is a non-nullable reference type. On success, the output follows T’s own nullability contract; if T is string?, a successfully retrieved element may also be null.
Omit the success or failure information only when the default value genuinely represents a missing value, or when the distinction is unnecessary.
Practical example: clearing an array
The parameter T?[] indicates that the caller must permit elements to be set to their default values. For int it is still int[]; for string it is string?[], whose elements may be null. Do not use default! merely to silence warnings and write null into an array whose elements are intended to be non-null. In ordinary code, you can also use Array.Clear; the loop here illustrates default.
Source code: DemoGenericClass
Generic attributes (C# 11)
Before C# 11, if you wanted to declare an attribute with a Type parameter, you had to write:
This is verbose and forces you to use the typeof operator. Starting in C# 11, you can declare a generic attribute:
Usage can directly specify the type argument:
The restriction is not just that the type argument must be fully constructed (for example, string rather than an open T). It must also satisfy the same limitations that apply to typeof(...) in attribute metadata. In other words, types such as dynamic and List<string?> still cannot be used as type arguments for generic attributes, because they cannot be represented there in a stable way.
More precisely, dynamic is treated as object at the CLR level, and the nullable annotation in string? is not part of the CLR type system, so neither can appear in attribute metadata in the way you might expect. This restriction ensures that the type arguments of a generic attribute can be represented in CLR metadata in a stable, well-defined way.
Source code: DemoGenericAttribute
7.3 Type parameter constraints
So far, we’ve used generics primarily to store values of different types.
However, generic code becomes much more useful when you need to interact with T—such as by calling its methods or accessing its properties. To do that safely, the compiler needs to know more about what T can do.
For example, suppose you want a generic list that can compare its items. You expect the items to have a CompareTo method, but without further information, the compiler cannot guarantee it:
The error is:
Tdoes not contain a definition forCompareToand no extension methodCompareToaccepting a first argument of typeTcould be found (are you missing a using directive or an assembly reference?)
Even if the type you eventually pass really has CompareTo, the compiler still cannot allow this code based on that hope alone.
Without any constraints, the compiler cannot assume that T has a specific member such as CompareTo. It can use only basic capabilities available to every type, such as Equals(), GetType(), and ToString().
This does not mean that T is “the same as object.” When the generic type is used, T may still be a value type such as int, or a reference type such as string or Employee. The important point is simply that without additional constraints, the compiler can safely assume very little about what T can do.
But that still does not solve the real need: sometimes you really do need to access specific members of the type argument inside generic code. At that point, do not try to solve the problem with an as cast like this:
This bypasses compile-time checks but risks runtime failure. Note that this uses the as operator, not an explicit cast. If obj1 doesn’t implement IComparable<T>, the as expression evaluates to null, and the subsequent .CompareTo(obj2) call can throw a NullReferenceException. The correct solution is the where clause.
The where clause
You can constrain a type parameter like this:
The where clause tells the compiler: any type argument for T must implement IComparable<T>. If not, compilation fails.
This is called a generic constraint. In practice, a constraint tells the compiler what capabilities a type parameter must provide.
Multiple constraints
You can require multiple interfaces and, optionally, a base class (only one base class is allowed because C# does not support multiple inheritance):
Rules:
- Only one base-class constraint.
- Multiple interface constraints are allowed.
- If you have a base class, it must come first.
class and struct constraints
class or struct can constrain reference types or value types:
With NRT enabled, class means a non-nullable reference type, while class? also permits nullable reference types. struct does not accept Nullable<T>. notnull permits non-nullable value or reference types, but violating a nullability constraint generally produces a compiler warning rather than a runtime check.
These primary constraints must come first in the constraint list:
new() constraint
If you need to create instances of T, you must add the new() constraint:
The new() constraint requires a nonabstract type with a public parameterless constructor, whether implicit or explicit. This makes new T() legal inside the generic type or method. An internal constructor is insufficient even within the same assembly.
Two rules:
Rule 1: new() usually comes last
If you use the C# 13 allows ref struct anti-constraint, that anti-constraint must appear after new().
Rule 2: new() cannot be combined with struct
struct already guarantees that new T() is valid, so new() would be redundant. Starting with C# 10, a struct can also declare its own parameterless constructor, but whether it uses the implicit one or a custom one, the struct constraint already guarantees that new T() can be used.
Common constraint combinations
Choose constraints according to the capabilities the generic implementation actually needs:
| Requirement | Example constraint |
|---|---|
| Accept non-nullable reference types | where T : class |
| Also accept nullable reference types | where T : class? |
| Accept non-nullable value or reference types | where T : notnull |
| Accept non-nullable value types | where T : struct |
| Call interface members and create instances | where T : IEntity, new() |
| Access members of a base class | where T : Entity |
For example, if a container requires an initial value, obtain it during construction:
Constraints express a type contract; they do not automatically initialize fields or validate arguments at runtime. See the official documentation on generic constraints for other combinations and ordering restrictions.
allows ref struct constraint (C# 13)
Before C# 13, a generic type parameter T did not allow ref struct types (such as Span<T> or ReadOnlySpan<T>) by default. This protects memory safety by preventing values with strict lifetime rules from escaping to the managed heap, for example through boxing.
However, this also limited the use of generic algorithms in high-performance scenarios. To address this, C# 13 introduced the allows ref struct anti-constraint:
This does not require T to be a ref struct; it permits T to be one. The generic implementation must obey the relevant lifetime and ref safety rules. See Chapter 13 for details.
Generic Math and operator constraints (.NET 7+)
Historically, one of the most common pain points in C# generics was the inability to apply operators like + or - to type parameters: even when constrained with where T : struct, the compiler could not guarantee that T supported addition.
Starting with .NET 7 / C# 11, C# supports static abstract interface members, and the BCL introduced Generic Math. Through the System.Numerics.INumber<T> constraint, generic algorithms can directly invoke arithmetic operators:
using System.Numerics;
// Constrained by INumber<T>, T can be int, double, decimal, or any
// numeric type
public T Add<T>(T left, T right) where T : INumber<T>
{
// ✔ Compiles! INumber<T> guarantees the existence of operator
// +
return left + right;
}
Console.WriteLine(Add(10, 20)); // 30
Console.WriteLine(Add(3.14, 2.71)); // 5.85This capability eliminates the long-standing limitation on generic arithmetic and serves as an essential building block for modern high-performance numerical and geometry libraries.
These constraint rules can look scattered, but in practice you usually add them step by step: add an interface constraint when you need to call an interface member, add new() when you need to create an instance, use INumber<T> when you need arithmetic operations, and consider allows ref struct only when you need to support types such as Span<T>.
Source code: DemoConstraints
Generic math in practice: random numbers (.NET 11)
Generic math supports both your own algorithms, such as the earlier Add<T>, and library APIs. .NET 11 provides Random.NextInteger<T> for different binary integer types:
INumber<T> alone would also admit floating-point types and is insufficient here. IBinaryInteger<T> specifies binary integer operations, and IMinMaxValue<T> supplies bounds.
NextBinaryFloat<T> uses IBinaryFloatingPointIeee754<T> and supports types such as float, double, and Half, but not decimal. These APIs suit simulations, not cryptographic secrets; use RandomNumberGenerator for those.
Source code: DemoGenericRandom
Related numeric APIs
.NET 11 also introduces
Complex<T>for choosing the precision of real and imaginary components, andDecimal32,Decimal64, andDecimal128with IEEE 754 decimal floating-point semantics, including infinities and NaN. These differ fromdecimal. Choose according to precision, range, and required interfaces. See .NET 11 numeric APIs.
Static interface members on older runtimes (C# 15)
Nonvirtual static interface helpers can now be used on older runtimes that do not support default interface implementations. This does not extend support for static abstract or virtual members, or default instance implementations; those still require runtime support. It does not affect this book’s .NET 11 examples. See Interface members.
7.4 Generic interfaces and structs
Generics also apply to interfaces and structs. Let’s start with interfaces, because they are often used to describe the contract that a family of generic types must follow.
Generic interface
For example, you can extract the list operations from MyGenericList<T> into a generic interface:
Then implement it:
public class MyGenericList<T> : IMyList<T>
{
private readonly List<T> _elements = new();
public int Count => _elements.Count;
public T this[int index]
{
get => _elements[index];
set => _elements[index] = value;
}
public void Add(T item) => _elements.Add(item);
public void Clear() => _elements.Clear();
}The rule is the same as normal interfaces: implement all required members.
Source code: DemoGenericInterfaces
Implementing generic interfaces
There are two approaches:
Option 1: keep the type parameter open
Option 2: close the type parameter
Both approaches compile. Option 2 is useful when you need a fixed type argument.
This does not compile:
If T is substituted with int, then ISayHello<T> becomes ISayHello<int>, which would make the same class implement the same interface twice. To prevent that potential conflict, the compiler rejects this declaration.
Generic structs
Generic structs use the same syntax as generic classes. A classic example is KeyValuePair<TKey, TValue>:
Usage:
The key point here is that generics are not limited to classes and interfaces; structs can also use type parameters to express “the types of this pair of values vary by use case.” KeyValuePair<TKey, TValue>, commonly used when iterating dictionaries, is a representative example of this design.
Source code: DemoGenericStructs
typeof and unbound generic types
Open generic types (like List<T>) and unbound generic types (like List<>) can both be represented at runtime as Type objects. What you cannot do is instantiate a generic type that has not yet been closed with actual type arguments. To create an instance, you must first construct a closed generic type such as List<int>.
That is because List<> is still missing its element type, so at runtime it cannot know whether you want to create List<int>, List<string>, or some other concrete version. In C#, the most common way to refer to an unbound generic type is typeof:
You can also specify closed types:
Type a3 = typeof(A<int, string>);Or, inside a generic class, you can retrieve the Type represented by the type parameter itself:
Practical use: reflection and generics
Once you know how to obtain an unbound generic type with typeof, you can fill in the actual type at runtime. The following example shows a pattern common in frameworks and containers: get Repository<>, then use MakeGenericType to create a closed type such as Repository<Customer>.
public class RepositoryFactory
{
public static object CreateRepository(Type entityType)
{
Type openType = typeof(Repository<>);
Type closedType = openType.MakeGenericType(entityType);
return Activator.CreateInstance(closedType)
?? throw new InvalidOperationException("Could not create an instance");
}
}
// Usage:
var customerRepo = RepositoryFactory.CreateRepository(typeof(Customer));
// Equivalent to new Repository<Customer>()This technique is useful in frameworks or containers that determine types at runtime. If the type is already known at compile time, ordinary generics are usually simpler. MakeGenericType checks that the type arguments satisfy the constraints; Activator may throw if construction fails or a constructor is missing. This is an advanced topic: with Native AOT or trimming, verify that the required types and members are available for reflection.
Source code: DemoUnboundGenericTypes
7.5 Generic methods
A generic method is a method with type parameters. It can live inside any class, struct, or interface, generic or not.
Basic syntax
Notes:
<T1, ..., Tn>are type parameters.(parameters)are formal parameters.- The
whereclause is optional.
Example:
Usage:
Type inference
If the compiler can infer type arguments from parameters, you can omit them:
The last call still needs explicit type arguments because C# generic method inference works primarily from the method arguments, not from the type of the variable receiving the return value. In other words, even if you assign the result to a DateTime variable, the compiler still cannot infer TResult from that alone.
Method-level vs class-level type parameters
If multiple methods share the same type parameter, you can move it to the class level:
Shadowing like Method3<T> is legal but produces compiler warning CS0693 and can be confusing, so avoid it. Here, the T in Method3<T> is a new method-level type parameter, not the same type parameter as the T in Demo<T>; the method can therefore use a different type from the class.
Generic extension methods
Extension methods can also declare their own type parameters and infer them from the caller’s arguments. Their implementation involves extension methods and delegates, so Chapter 11 covers this topic. For now, focus on type inference and scope in ordinary generic methods.
Source code: DemoGenericMethods (Run the extension-method example after reading Chapter 11.)
Next, we look at compatibility between generic types: when does the compiler reject an assignment that seems reasonable?
7.6 Covariance and contravariance
Bruce: “Tell me, is a string an object?”
Robin: “Of course.” (Too easy.)
“Then is a list of strings a list of objects?”
Robin hesitates, but says yes.
“Good,” Bruce says. “What if I assign a
List<String>to aList<Object>? Does it compile? Or does it compile but fail at runtime?”Robin: “Uh…”
To answer that question, we need to explore how generic types are compatible with one another. The key concepts are covariance and contravariance, introduced for generics in C# 4. They can feel abstract at first, so we will work through them with examples.
Type compatibility basics
All variance concepts are about type safety, especially compile-time checks. They describe when one type can be treated as another compatible type.
These ideas existed before .NET 4: C# arrays are covariant.
In C#, a value of a derived reference type can be assigned to a variable of its base type:
Here is the same rule shown with arrays:
But this is unsafe. The problem is that the compiler lets you put a DateTime into an object[], even though that array is really still a string[]. You can see the issue more clearly here:
The last line throws an ArrayTypeMismatchException at runtime.
In other words, array covariance lets some type mismatches slip past compile time and fail only at runtime. Generic collections use stricter rules by default so errors like this are caught earlier. That is one important value of generic collections.
Invariance of generics
Many readers first see this and instinctively think, “If string is an object, shouldn’t List<string> also count as a List<object>?” But this is still not allowed:
You get:
Cannot implicitly convert type System.Collections.Generic.List<string>
to System.Collections.Generic.List<object>
Why is this forbidden? The type parameter of List<T> is invariant. If this assignment were allowed, callers could use objectList.Add(42) to add an integer to a list that can contain only strings. The compiler forbids the conversion to preserve the original type contract.
Even though string derives from object, List<string> does not derive from List<object>.
Covariance
Although List<string> cannot be treated directly as List<object>, that restriction can feel inconvenient in scenarios where you only need to read the elements. Covariance helps in those scenarios that only require reading elements. Starting with C# 4, you can do:
IEnumerable<T> is covariant because its definition uses out:
out T means T only appears in output positions, which preserves type safety:
Because T is output-only, using IProducer<string> as IProducer<object> is safe.
Contravariance
Contravariance uses in and restricts T to input positions:
This allows:
If something can consume any object, it can consume a string.
Example: comparers
IComparer<T> is contravariant:
Because IComparer<in T> is contravariant:
Variance in delegates
Generic delegates can also express variance through in and out. Chapter 8 uses Func and Action to explain these conversions. For now, focus on the input and output directions of interfaces.
A simple memory aid
These two terms are easy to mix up. A useful approach is to remember the direction first, then come back to where out and in appear:
- out = output = covariance: producer. If you can produce a more specific type, you can be used where a more general type is expected.
- Direction: Child → parent
- in = input = contravariance: consumer/tool. If you can consume a general type, you can also consume a more specific type.
- Direction: Parent → child

Limitations
Variance applies only to:
- Generic interfaces
- Generic delegates
It does not apply to:
- Generic classes (
List<T>does not support variance conversions; invariance here is different from immutability in Chapter 4) - Generic structs
- Generic method type parameters
Also note that declaring out / in does not require a class constraint:
However, variance conversions only happen when the generic type is constructed with a reference type. If the type argument is a value type, that conversion does not apply. That is because variance relies on type-compatible reference conversions; converting int to object requires boxing, which is not the same kind of direct reference conversion, so you must handle it explicitly:
Source code: DemoCovariance
Remember the key point: if a generic type both accepts T and returns T, you usually cannot freely make it covariant or contravariant. Only interfaces and delegates with a clear direction are good candidates for out or in.
7.7 Performance characteristics of generics
Next, let’s look at a few runtime characteristics of generics. They are helpful when evaluating collections, performance, or static field behavior.
Generic vs non-generic collections
The ArrayList and List<int> examples in Section 7.1 already show the boxing difference. Generic collections store int values directly and avoid that boxing and unboxing, but not every generic operation avoids boxing: converting a value of T to object can still require it. Next, consider static state and code sharing in generic types.
Generics and memory
Each closed constructed type gets its own static fields. For example:
public class Singleton<T> where T : new()
{
private static T _instance = new T();
public static T Instance => _instance;
}
// These two reads access separate static instances for different
// constructed types
var intSingleton = Singleton<int>.Instance;
var listSingleton = Singleton<List<string>>.Instance;In other words, static fields belong to concrete types such as Singleton<int> and Singleton<List<string>>, not to the generic definition Singleton<T> before T has been specified.
Therefore, whenever the type argument differs, you should treat the result as a different constructed type. This is especially important when designing caches, singletons, or static state.
Type specialization and code sharing in JIT mode
When you see constructed types such as List<int>, List<string>, and List<Employee>, you may wonder whether the runtime generates separate machine code for every type. This affects code size and some performance characteristics, and .NET’s answer is not simply “all shared” or “all separate.”
In the usual JIT execution model, .NET retains generic type information until runtime. The JIT compiler then decides how to generate machine code for each constructed type. The typical cases are:
- Reference types: Constructed types whose type argument is a reference type can usually share most of their machine code. For example,
List<string>andList<Employee>can share most of the generic implementation. - Value types: The runtime usually generates specialized versions for different value types, so
List<int>andList<double>can have their own machine code.
Different reference types have the same machine-level representation as object references, while value types can differ in size, layout, and available operations. This gives the JIT opportunities to produce more specific code for value types.
Note
This describes typical behavior in the usual JIT execution model, not a fixed process shared by every .NET deployment model. With Native AOT, the application is compiled into native code during publishing, so there is no runtime step in which the JIT “expands” its generic types.
This also explains why “a template for a type” is only a useful metaphor. .NET preserves generic type arguments in its metadata and type system, while the deployment model and runtime determine the actual machine code. In everyday API design, avoid relying on one fixed code-sharing strategy. If code size or execution performance matters, measure it using the deployment model you actually plan to use.
7.8 Practical guidelines
This section focuses on when to use generics and what to watch for when designing generic APIs.
When to use generics
Good fits:
- Collection classes (List, Dictionary, Queue, etc.)
- Data-structure algorithms (sorting, searching)
- Factory pattern
- Repository pattern
- Result/Option types
Situations requiring careful evaluation or poor fits:
- Too many type parameters with tangled responsibilities: When a class or method needs many type parameters, check whether the API mixes different responsibilities. Examine whether each type parameter truly represents an independent data contract. If parameters represent configuration, logging, or helper services, prefer constructor injection, interfaces, or composition over crowding angle brackets (see Principle 1 below).
- Logic tightly coupled to concrete implementations: If method logic relies heavily on specific properties or private details of concrete types, using generics forces you to rely on
is,as, or casting to inspect types—undermining the core value of compile-time type safety. In such cases, prefer ordinary concrete methods, interface contracts, composition/strategy patterns, or inheritance when an “is-a” relationship genuinely applies. - Heavy reliance on dynamic reflection or Native AOT constraints: If an algorithm depends heavily on runtime type inspection and dynamically constructing generic types (e.g., via
MakeGenericType), generics add code complexity, incur performance overhead, and can introduce trimming and code-generation compatibility risks under Native AOT. Simpler non-generic interfaces or polymorphic abstractions are often much more practical.
Designing generic APIs
Good generic API design keeps caller code clear. Poor design makes type parameters and angle brackets harder to read than the actual logic. Here are some principles:
Principle 1: minimize type parameters
The more type parameters you add, the harder it is for callers to see what role each one plays. If some of those dependencies are not really part of the data type itself, constructor injection, interfaces, or configuration objects often express the design more clearly.
Principle 2: use meaningful names
A single type parameter named T is common, but when a type parameter has a clear role, names like TKey and TValue make the API’s intent visible right in the signature.
Principle 3: use constraints appropriately
Constraints are not about making a type look stricter; they are about telling the compiler what capabilities the method actually needs. That moves mistakes to the call site instead of letting them surface later at runtime.
Principle 4: prefer generic interfaces
If a method only needs to enumerate elements, keep the parameter at a smaller contract such as IEnumerable<T>. That preserves caller flexibility and makes the method easier to reuse.
AI-assisted development with generics
When using AI to write generic code, check not only whether it compiles, but also whether it expresses the right type contract.
Pitfall 1: missing constraints
For example, CompareTo in Section 7.3 cannot compile without the IComparable<T> constraint. Instead of merely asking AI to fix the error, check whether the added constraint provides exactly the capability you need.
Note: syntax shorthand and style preferences
Both default(T) and target-typed default are valid. More important than style preferences is whether a default value could be mistaken for valid data, and whether nullability annotations match the method’s behavior.
Example prompt:
Run these tests and confirm the results match the method contract.
Summary
- Constructed types can be open or closed; these classifications describe different properties of a type.
- .NET 11 generic random APIs use numeric constraints to support several integer and binary floating-point types.
This chapter covered the core concepts and practical use of generics:
- Value of generics: Type safety, performance, and reuse
- Type parameters: Generic definitions, constructed types, and open vs closed types
- Type parameter constraints:
class/struct/new() - Generic interfaces and methods: Flexible abstraction
- Covariance and contravariance: Using
outandin - Practical guidance: When to use generics and how to design APIs
In the next chapter, we’ll learn how to pass methods as arguments using delegates. Chapter 9 then introduces event-driven programming.
Exercises
Exercise 1: Implement a generic stack
Implement a generic stack MyStack<T> that supports:
Push(T item)Pop()(returns the top item)Peek()(returns the top item without removing it)Countproperty
Requirements:
- Use an array internally
- Auto-grow when capacity is insufficient
PopandPeekshould throwInvalidOperationExceptionwhen empty- After Pop removes an element, clear the unused storage slot to avoid retaining references. Verify empty-stack behavior, capacity growth, and last-in-first-out order.
Exercise 2: Implement a generic pair
Implement a Pair<T1, T2> class that stores two values and implements IEquatable<Pair<T1, T2>> for equality comparison. Verify that equal objects have equal hash codes, including cases where either element may be null.
Exercise 3: Generic arithmetic in practice (Generic Math Challenge)
Using Generic Math introduced in Section 7.3, implement a generic method that computes the average of a numeric collection satisfying the following constraint:
Questions to consider:
- How can
T.Zeroinitialize the sum? How do integer and floating-point division differ? - How should an empty sequence be handled? What contract governs sum overflow, conversion of the element count, and integer division? Test at least an empty sequence, integer [1, 2], and floating-point [1.0, 2.0].
- (After Chapter 8) On older .NET versions without Generic Math, how could operation delegates such as
Func<T, T, T>or strategy objects be injected through constructors to achieve a similar algorithm?
Exercise 4: Covariance in practice
Assume this class hierarchy:
Design an IAnimalShelter<T> interface so that IAnimalShelter<Dog> can be assigned to IAnimalShelter<Animal>.
Glossary
| Term | Description |
|---|---|
| Boxing | Converting a value type into a reference type (object) |
| Closed type | A type with no remaining type parameters |
| Constructed type | A generic definition with type arguments substituted; it may be open (List<T>) or closed (List<int>) |
| Contravariance | in allows a wider type such as IComparer<object> to be used safely as IComparer<string> |
| Covariance | out allows a narrower type such as IEnumerable<string> to be used safely as IEnumerable<object> |
| Generic constraint | Same as type constraints |
| Generic method | A method that has type parameters |
| Generic type | A parameterized type definition |
| Invariance | Does not permit variance conversions between corresponding generic types based on inheritance between type arguments |
| Open type | A type involving type parameters, such as T, T[], or List<T> |
| Reflection | Inspect and manipulate type info at runtime |
| Type constraint | Use where to restrict type parameters |
| Type inference | Compiler infers type arguments from method arguments |
| Type parameter | The <T> in generics, such as <TKey, TValue> |
| Unbound generic type | Type object from typeof(List<>) |
| Unboxing | Extracting a value of a value type from a boxed object |