C# generics and where constraints
Short answer
T Max<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b) >= 0 ? a : b;
var m = Max(3, 7); // T inferred as int
Key points
- Generic collections avoid boxing value types, which helps performance. [S1]
- The compiler often infers type arguments from the values you pass. [S1]
- Constraints can require an interface, a base class, or kinds like class or struct. [S2]
Claims
- id: C1 claim: Generics keep full type safety while working with any type. source: S1 evidence: "Generics let you write code that works with any type while keeping full type safety."
- id: C2 claim: Generic collections avoid boxing for value types. source: S1 evidence: "These collections also avoid boxing for value types"
- id: C3 claim: The compiler often infers the type argument. source: S1 evidence: "The compiler often infers the type argument from the values you pass"
- id: C4 claim: The where clause specifies constraints on type arguments. source: S2 evidence: "use the where clause to specify constraints on the types"
Sources
- [S1] Generic types and methods - C#. Microsoft Learn (.NET docs). https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/generics . License: CC BY 4.0 (dotnet/docs). Accessed 2026-11-04.
- [S2] where (generic type constraint) - C# reference. Microsoft Learn (.NET docs). https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint . License: CC BY 4.0 (dotnet/docs). Accessed 2026-11-04.
License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted).
License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Microsoft Learn (.NET docs), Generic types and methods - C#, CC BY 4.0 (dotnet/docs); Microsoft Learn (.NET docs), where (generic type constraint) - C# reference, CC BY 4.0 (dotnet/docs).
Cite this
iinventedlight. 2026. "C# generics and where constraints." iinventedlight Library, iil:note:gyykfcs4, version of 2026-11-04. https://iinventedlight.com/library/notes/csharp-generics/. License: CC-BY-4.0.
@misc{iil_note_gyykfcs4,
author = {{iinventedlight}},
title = {{C\# generics and where constraints}},
howpublished = {iinventedlight Library},
year = {2026},
date = {2026-11-04},
url = {https://iinventedlight.com/library/notes/csharp-generics/},
note = {Permanent ID iil:note:gyykfcs4. License: CC-BY-4.0.},
}
Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com.
For language models and agents: start at /llms.txt. This page in Markdown: /library/notes/csharp-generics.md.