skip to content

In C#, why does a generic method constrained with `where T : IComparable<T>` call CompareTo on an int without boxing, while an `IComparable<int>` parameter boxes it?

level: seniorimportance: should knowfreq 35%

answer

  1. what the call site knows about T
  2. a prefix on the call instruction
  3. a native body per value type
  4. inherited members still need a box

basics

~20 s

Inside the generic method the compiler emits a constrained call on the T value itself, and for an int the JIT turns it into a direct call to Int32.CompareTo. An IComparable<int> parameter is a reference, so the int must be boxed to pass it.

solid answer

~40 s

Passing an `int` to an `IComparable<int>` parameter is an interface conversion, and that boxes. In `ViaGeneric<T>(T left, T right) where T : IComparable<T>`, `left` stays a `T`; the compiler emits a `constrained.` prefix on the `callvirt` to `CompareTo`, and because the runtime compiles a dedicated body for each value-type instantiation, the call for `int` becomes a direct call to `Int32.CompareTo(int)` on the value. Measured on .NET 10: 24,000 bytes per 1,000 calls through the interface parameter, 0 through the generic. A constrained call still boxes when the struct does not implement the member itself: `GetHashCode`, `ToString` or `Equals` inherited from `ValueType` need a boxed receiver. Explicitly converting a `T` to `object` or to the interface is a boxing conversion too.

code

csharp · 30 lines
csharp
const int Calls = 1_000;
var plain = new Reading(3, 4);
var tuned = new TunedReading(3, 4);

Console.WriteLine($"IComparable<int> parameter:   {Measure(() => { for (int i = 0; i < Calls; i++) Compare.ViaInterface(i, 5); })} bytes");
Console.WriteLine($"T : IComparable<T> parameter: {Measure(() => { for (int i = 0; i < Calls; i++) Compare.ViaGeneric(i, 5); })} bytes");
Console.WriteLine($"GetHashCode, not overridden:  {Measure(() => { for (int i = 0; i < Calls; i++) Compare.Hash(plain); })} bytes");
Console.WriteLine($"GetHashCode, overridden:      {Measure(() => { for (int i = 0; i < Calls; i++) Compare.Hash(tuned); })} bytes");

static long Measure(Action body)
{
    long before = GC.GetAllocatedBytesForCurrentThread();
    body();
    return GC.GetAllocatedBytesForCurrentThread() - before;
}

static class Compare
{
    public static int ViaInterface(IComparable<int> left, int right) => left.CompareTo(right);           // the int argument is boxed
    public static int ViaGeneric<T>(T left, T right) where T : IComparable<T> => left.CompareTo(right);  // constrained call, no box
    public static int Hash<T>(T value) where T : struct => value.GetHashCode();                          // boxes only if T inherits it
}

readonly struct Reading(int x, int y) { public readonly int X = x, Y = y; }

readonly struct TunedReading(int x, int y)
{
    public readonly int X = x, Y = y;
    public override int GetHashCode() => HashCode.Combine(X, Y);
}

go deeper

for a junior

Recall that an interface-typed parameter boxes a struct argument, while a generic method constrained to that interface can call its members without a box.

for a middle

Explain the constrained call: the compiler emits it on the T value, and for a struct that implements the member, the struct's own method runs directly on the value.

for a senior

Find where generic code still boxes, such as inherited ValueType members, explicit casts to object or the interface, and object-typed helpers, and fix them by overriding or calling through T.

for a principal

Decide which hot APIs earn constrained generic signatures over interface parameters, trading harder-to-read signatures and a native body per value type for zero boxing.

## Two signatures, two outcomes Both methods below call `CompareTo` on an `int`. Only one allocates: | Signature | What the argument is at the call | Allocation per call (.NET 10, `int`) | |---|---|---| | `ViaInterface(IComparable<int> left, int right)` | a reference to a box holding the `int` | 24 bytes | | `ViaGeneric<T>(T left, T right) where T : IComparable<T>` | the `int` value itself | 0 bytes | In the first, the caller converts the `int` to the interface type. Interfaces are reference types, so that is a **boxing conversion**: a heap object is allocated and the value copied into it, once per call. In the second, the parameter's type is `T`, and for `ViaGeneric<int>` that is `int`; no conversion happens at the call site. ## What the compiler emits The interface constraint is what lets the body call `left.CompareTo(right)` at all. For a member call on a value of type `T`, the C# compiler does not convert `left` to `IComparable<T>`. It emits the `callvirt` with a **`constrained.` prefix** naming `T`. The IL of a generic `value.ToString()` in the probe used for this answer carries the `constrained.` prefix (opcode bytes `FE 16`) before its `callvirt` and contains no `box` instruction, while converting an `int` to `IComparable<int>` compiles to a `box`. When the method runs, the runtime resolves the constrained call for the actual `T`: 1. **`T` is a reference type** (say `string`): the value already is a reference, so the call is an ordinary virtual call on it. 2. **`T` is a value type that implements the member** (`int` implements `CompareTo(int)`): the struct's own method is called directly on the value's storage, with no box. 3. **`T` is a value type that only inherits the member** (a struct without its own `GetHashCode`): the method's implementation lives on the class `System.ValueType`, which needs an object as its receiver, so the value is boxed and the call is made on the box. Case 2 is practical because CoreCLR compiles a separate native body for each value-type instantiation (`ViaGeneric<int>`, `ViaGeneric<double>`), while reference-type instantiations share one body. The details of that code sharing belong with the runtime material; for this question it means the JIT knows `T` is exactly `int` and can call `Int32.CompareTo` directly. ## Measured on .NET 10 The snippet for this question runs 1,000 calls of each kind, with the same results in Debug and Release builds: - `IComparable<int>` parameter: 24,000 bytes. - `T : IComparable<T>` parameter: 0 bytes. - `Hash<T>(T)` calling `GetHashCode()` on a struct that does not override it: 24,000 bytes. - The same call on a struct that overrides `GetHashCode`: 0 bytes. So the constraint removes the box only for members the struct implements itself. The Debug and Release numbers match because the constrained call is part of the IL's meaning, not an optimization the JIT may or may not apply: an unoptimized build gets the same direct call. ## Where generic code still boxes - **Inherited members.** `ToString`, `GetHashCode` and `Equals(object)` on a struct that does not override them (case 3 above). - **Explicit conversions.** `object o = value;` or `(IComparable<T>)value` is a boxing conversion when `T` is a struct. The optimizing JIT can sometimes remove a box that never escapes, but Debug and not-yet-optimized code allocate it, so do not rely on that. - **Object-typed helpers.** Passing a `T` to `string.Format`, a non-generic logger or an `ArrayList` boxes it like any other value. - **Equality through `object`.** Calling `Equals(object)` boxes the argument; equality APIs built on `IEquatable<T>` avoid that, as covered with equality and hashing. ## Writing generic code that does not box 1. **Constrain, do not accept.** For hot paths, take a type parameter constrained to the interface instead of a parameter of the interface type. 2. **Call members on the `T`.** Write `value.CompareTo(other)`, not `((IComparable<T>)value).CompareTo(other)`. 3. **Pass by `ref` to mutate.** A constrained call on a `ref T` parameter acts on the caller's variable. 4. **Override inherited members** on structs that flow through generic code (`GetHashCode`, `Equals`, `ToString`). 5. **Prefer generic helpers from the BCL.** `EqualityComparer<T>.Default.Equals(a, b)` measured zero allocations for `int` on .NET 10, because the default comparer for a type that implements `IEquatable<T>` calls the typed `Equals`. 6. **Measure.** `GC.GetAllocatedBytesForCurrentThread()` around a loop is enough to confirm a zero. How `where` clauses are declared and combined is covered with generic constraints; the point here is what the constrained call does to a struct.

  • Why does a constrained GetHashCode() call still box when T is a struct that does not override it?
    The constrained call runs the struct's own implementation when it has one. Without an override, the implementation is `ValueType.GetHashCode`, an instance method of a class, which needs an object reference as its receiver. The runtime therefore boxes the value and makes an ordinary virtual call on the box. Overriding the member in the struct removes that box.
  • Inside the generic method, does ((IComparable<T>)value).CompareTo(other) box when T is int?
    The cast is a boxing conversion, and the compiler emits a `box` instruction for it. The optimizing JIT can remove a box that never escapes: on .NET 10 it allocated 24 bytes per call in a Debug build and nearly nothing when fully optimized, which is not a guarantee to build on. Calling `value.CompareTo(other)` directly needs no box in any build.
  • Does ViaGeneric box when T is a reference type such as string?
    No. A `string` is already a reference, so the constrained call becomes an ordinary virtual call on it and nothing is allocated. Reference-type instantiations share one compiled body; each value-type instantiation gets its own, which is what lets the runtime call `Int32.CompareTo` directly for `int`.

  • A generic method constrained to an interface boxes value types just like an interface parameter.
  • Constrained calls never box, whatever members the struct implements.
  • Generic code works on object internally, so every T is boxed.
  • Casting T to the constraint interface is free because T already implements it.
  • Overriding GetHashCode on a struct makes no difference to allocations.