A practical tour of C# generics, from type inference and primary-constructor wrappers to the ten where constraints and generic math with INumber<T>, plus the boxing costs that made generics necessary in the first place.
Key points
- Unconstrained T exposes only object members, so == does not compile without a constraint or EqualityComparer<T>.Default.
- Combining constraints follows a fixed order: class or struct first, interfaces in the middle, new() last.
- Generic math landed in .NET 7 via static abstract interface members; Sum<T> where T : INumber<T> serves int, double and decimal.
- The unmanaged constraint allows pointer operations and interop, while notnull rejects null for both reference and value types.
- A readonly struct Result<T> with Success and Failure factories avoids throwing exceptions for expected business failures.
- The snippets target .NET 10 / C# 14 and use primary constructors on generic types such as Box<T>(T value).
Why it matters
Most .NET developers consume generics daily through List<T> and Dictionary<TKey, TValue> but rarely write their own constrained abstractions, and that is exactly where small mistakes cost hours in review. Knowing the constraint ordering rules and the EqualityComparer<T>.Default fallback is what separates a generic helper that works for every type from one that compiles only for strings.
Before adopting generic math, check your target frameworks: INumber<T> needs .NET 7 or later, so libraries that still multi-target netstandard2.0 keep duplicated numeric overloads. Also be deliberate about T? return annotations, since default yields a different value for reference and value types. Port the helpers you actually repeat, not everything at once.
Real-world use
- APIs that return Result<T> rather than throwing for expected business failures like an invalid user ID.
- An in-memory repository constrained to class, IEntity and new() that creates and stores entities by Id.
- A Sum<T> helper built on INumber<T> that serves int, double and decimal collections without duplicate overloads.
- A non-boxing Contains helper that leans on EqualityComparer<T>.Default for string tags and int arrays.
This summary was generated by the agent from the original post on Khalid Abuhakmeh. The full text and all rights belong to its author and publisher. Go to original