Skip to main content
Journey Uncommon Logo
JourneyUncommon
hardC#boxing and unboxing costSingle-choice MCQ

Consider an interface call on a value type held directly (not through an interface variable). Why can `list.Sort()` using a struct comparer be allocation-free while passing that same struct as an `IComparer<T>` argument boxes it?

struct MyCmp : IComparer<int> { public int Compare(int a, int b) => a - b; } // Array.Sort(arr, new MyCmp()); // boxes // arr.AsSpan().Sort(new MyCmp()); via generic constraint -> no box