Constraints and inference
Constraints and inference
A constraint is a compile-time requirement on a type argument. Write where T : IComparable<T> when your algorithm needs the CompareTo operation. The compiler checks the supplied type and permits the constrained member inside the method. Select the least restrictive constraint that expresses the actual required operation.
Common constraints: class expects a non-nullable reference type in the enabled nullable context; class? permits nullable reference annotations too. struct requires a non-nullable value type, unmanaged additionally rules out managed references recursively, and notnull expresses a non-nullable reference or value type (violations generally produce nullable warnings). A base class or interface constraint supplies its available members. new() requires a public parameterless constructor and a non-abstract type; put it after ordinary constraints. It is redundant and invalid with struct or unmanaged. C# 13 introduced allows ref struct, an anti-constraint that permits ref-like arguments while requiring the implementation to obey ref-safety rules; it belongs last. Do not add it casually. default is a specialized override/explicit-interface-implementation constraint, not a way to request default values.
using System;Console.WriteLine(Smaller(7, 3));Console.WriteLine(Smaller(9, 9));Console.WriteLine(Smaller(new Rank(5), new Rank(2)).Level);static T Smaller<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b) <= 0 ? a : b;record Rank(int Level) : IComparable<Rank>{ public int CompareTo(Rank? other) => other is null ? 1 : Level.CompareTo(other.Level);}CompareTo provides an ordering contract: negative, zero or positive. The method retains the first item on a tie. IComparable<T> alone is not a runtime non-null check; this helper assumes non-null operands. An API accepting external reference inputs should validate them or define null ordering.
Expected output (reasoned, not executed):
392Supply a type argument when no argument reveals T
using System;var item = Create<Badge>();Console.WriteLine(item.Name);Console.WriteLine(Repeat(6).Second);static T Create<T>() where T : new() => new T();static (T First, T Second) Repeat<T>(T value) => (value, value);class Badge{ public string Name { get; } = "New badge"; public Badge() { }}Create has no ordinary arguments to infer T from, so the caller specifies Badge. Repeat can infer int from 6. A return target or constraint alone does not determine generic method type inference.
Expected output (reasoned, not executed):
New badge6Use a numeric interface instead of type checks
using System;using System.Numerics;using System.Globalization;Console.WriteLine(Sum(2, 3));Console.WriteLine(Sum(1.25m, 2.50m).ToString("0.00", CultureInfo.InvariantCulture));static T Sum<T>(T a, T b) where T : INumber<T> => a + b;C# 11 and .NET 7 introduced the language/library combination for generic math used here. The numeric interface supplies static abstract operator contracts, so the compiler can bind addition on T. It does not force all numeric types to share rounding, range or overflow behavior.
Expected output (reasoned, not executed):
53.75Common mistakes and edge cases
Avoid trying where T : int; use a supported interface, base class or special constraint. new() is not permission to construct with arbitrary parameters. A generic notnull constraint does not validate values at runtime. Unconstrained T? in modern nullable-enabled C# describes a possibly absent/default result in a type-dependent way; it does not always mean Nullable<T>. The separate inference diagnostic fixture illustrates a call where the compiler cannot infer T. Use explicit type arguments or redesign the input contract.
Practice and next steps
Implement Greater<T>(T a, T b) with an IComparable<T> constraint; return a when equal. Test (2,8), (8,2), (5,5) and decimal (1.25m,1.20m). Then explain why Greater(new object(), new object()) is rejected.
Next: Variance and interface contracts.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Constraints and inference — knowledge check
Apply the lesson concepts to the following scenarios.
Which constraint supplies CompareTo(T)?
Why must Create<T>() be called with a type argument in the example?
What does where T : new() require?
Does notnull guarantee an input value is not null at runtime?
Why can Sum<T> use + with INumber<T>?