You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[API Proposal]: Array GetValue SetValue ROS indices #125325
Is this really a bottleneck? The GetValue/SetValue apis are boxing, and the overhead of boxing primitive types can easily overtake the overhead of index array.
Array.GetValue(params int[]) and Array.SetValue(object?, params int[]) require allocating an int[] for the indices when iterating multi-dimensional arrays of unknown rank. This is a friction point for libraries like Npgsql that work with multi-dimensional arrays where the rank is only known at runtime -- they must either allocate an int[] per call or pool index arrays across method boundaries (including across async methods where stackalloc cannot be used).
Internally, Array.GetFlattenedIndex already accepts ReadOnlySpan<int>, so the implementation is trivially a public API surface addition.
API Proposal
namespaceSystem;publicpartialclassArray{// EXISTING// public object? GetValue(params int[] indices);// public void SetValue(object? value, params int[] indices);publicobject?GetValue(paramsReadOnlySpan<int>indices);publicvoidSetValue(object?value,paramsReadOnlySpan<int>indices);}
API Usage
// Iterating a multi-dimensional array of unknown rank without allocating per-callArrayvalues=...;intdimensions=values.Rank;varindicesArray=ArrayPool<int>.Shared.Rent(dimensions);varindices=indicesArray.AsSpan(0,dimensions);indices.Clear();do{varvalue=values.GetValue(indices);// process value}while(IncrementIndices(indices,values));ArrayPool<int>.Shared.Return(indicesArray);
// Using stackalloc for a known-rank iteration patternArrayvalues=...;Span<int>indices=stackallocint[values.Rank];indices.Clear();do{varvalue=values.GetValue(indices);// process value}while(IncrementIndices(indices,values));
Design Decisions
No ReadOnlySpan<long> overloads. The existing long-based overloads internally cast to int and throw ArgumentOutOfRangeException on overflow. They exist for CLS compliance from .NET Framework. New span overloads for long would serve no practical purpose since array dimensions are bounded by int.
params modifier included. This enables the natural call syntax array.GetValue(1, 2, 3) to resolve to the span overload in C# 13+, avoiding the int[] allocation in expanded form. The existing fixed-arity overloads GetValue(int), GetValue(int, int), GetValue(int, int, int) are still preferred by overload resolution in normal form for 1-3 indices.
Alternative Designs
Generic element-typed overloads (GetValue<T>(params ReadOnlySpan<int> indices) / SetValue<T>(T value, params ReadOnlySpan<int> indices)) were explored to avoid boxing for value-type elements. This is technically feasible -- MemoryMarshal.GetArrayDataReference(Array) combined with GetFlattenedIndex and Unsafe.As<byte, T> can provide unboxed access. However:
The use case is narrow: you must know T but not the rank at compile time. If you know the rank, you can use the strongly-typed indexer (e.g., int[,] indexer).
Runtime type validation adds overhead (comparing typeof(T) against the array's element type).
The non-generic SetValue supports implicit primitive widening (e.g., storing int into long[]), which a generic version would not.
For reference types, there is no boxing, so the benefit is limited to value-type elements.
This could be a follow-up proposal if demand materializes.
Risks
Overload resolution change (source-compatible). In C# 13+, calls in expanded form like array.GetValue(i, j, k, l) (4+ args) will prefer the new params ReadOnlySpan<int> overload over params int[]. The behavior is identical -- both delegate to the same GetFlattenedIndex(ReadOnlySpan<int>) -- so this is a benign overload resolution change. Calls with 1-3 args still resolve to the existing fixed-arity overloads. Calls in normal form with an explicit int[] argument still resolve to the int[] overload.
Open Questions
Should the GetFlattenedIndex(ReadOnlySpan<int>) method itself be made public? It would allow advanced callers to compute flat indices for use with MemoryMarshal.GetArrayDataReference, enabling zero-allocation generic access patterns. This is a more advanced API that could be proposed separately.
@eiriktsarpalisGetFlattenedIndex would help us support multi-dim Nullable<TEnum> via Nullable<TUnderlying> conversions. Postgres doesn't support jagged arrays, everything 'nested' is multidimensional.
Without GetFlattenedIndex we'd be duplicating the runtime's row-major stride logic, which is documented at the ECMA-335 level but is the exact kind of code that we don't really want to have to own.
As there is no CLR array variance through Nullable<> we cannot use Array.SetValue/GetValue for these conversions. Without GetFlattenedIndex we have no BCL primitive to do this for multidims: just doing Unsafe.As<int?[,]> on the nullable enum-typed array instance isn't a valid reinterpretation. So the only sound shape is per-element ref-cast starting from the actual array data reference, which is legal for layout-equivalent blittable value types but requires a flat-index to address the slot.
Whether GetFlattenedIndex is exposed or not, the access pattern still goes through ref-byte reinterpretation over an erased Array instance produced by Array.CreateInstanceFromArrayType (AOT compatible, since we don't have per-Nullable<UnknownEnum> conversions rooted). So this doesn't lead to prettier code on our end, but it does create more maintainable code to bridge layout-equivalent multi-dim slot access.
Activity
dotnet-policy-service commentedon Mar 9, 2026
Tagging subscribers to this area: @dotnet/area-system-collections
See info in area-owners.md if you want to be subscribed.
huoyaoyuan commentedon Mar 9, 2026
Is this really a bottleneck? The
GetValue/SetValueapis are boxing, and the overhead of boxing primitive types can easily overtake the overhead of index array.NinoFloris commentedon Mar 9, 2026
We send plenty of reference type arrays as well. These are simple avoidable allocations, and ROS is used internally already.
dotnet-policy-service commentedon Mar 9, 2026
Tagging subscribers to this area: @dotnet/area-system-runtime
See info in area-owners.md if you want to be subscribed.
eiriktsarpalis commentedon Mar 9, 2026
Background and motivation
Array.GetValue(params int[])andArray.SetValue(object?, params int[])require allocating anint[]for the indices when iterating multi-dimensional arrays of unknown rank. This is a friction point for libraries like Npgsql that work with multi-dimensional arrays where the rank is only known at runtime -- they must either allocate anint[]per call or pool index arrays across method boundaries (including acrossasyncmethods wherestackalloccannot be used).Internally,
Array.GetFlattenedIndexalready acceptsReadOnlySpan<int>, so the implementation is trivially a public API surface addition.API Proposal
API Usage
Design Decisions
No
ReadOnlySpan<long>overloads. The existinglong-based overloads internally cast tointand throwArgumentOutOfRangeExceptionon overflow. They exist for CLS compliance from .NET Framework. New span overloads forlongwould serve no practical purpose since array dimensions are bounded byint.paramsmodifier included. This enables the natural call syntaxarray.GetValue(1, 2, 3)to resolve to the span overload in C# 13+, avoiding theint[]allocation in expanded form. The existing fixed-arity overloadsGetValue(int),GetValue(int, int),GetValue(int, int, int)are still preferred by overload resolution in normal form for 1-3 indices.Alternative Designs
Generic element-typed overloads (
GetValue<T>(params ReadOnlySpan<int> indices)/SetValue<T>(T value, params ReadOnlySpan<int> indices)) were explored to avoid boxing for value-type elements. This is technically feasible --MemoryMarshal.GetArrayDataReference(Array)combined withGetFlattenedIndexandUnsafe.As<byte, T>can provide unboxed access. However:Tbut not the rank at compile time. If you know the rank, you can use the strongly-typed indexer (e.g.,int[,]indexer).typeof(T)against the array's element type).SetValuesupports implicit primitive widening (e.g., storingintintolong[]), which a generic version would not.This could be a follow-up proposal if demand materializes.
Risks
Overload resolution change (source-compatible). In C# 13+, calls in expanded form like
array.GetValue(i, j, k, l)(4+ args) will prefer the newparams ReadOnlySpan<int>overload overparams int[]. The behavior is identical -- both delegate to the sameGetFlattenedIndex(ReadOnlySpan<int>)-- so this is a benign overload resolution change. Calls with 1-3 args still resolve to the existing fixed-arity overloads. Calls in normal form with an explicitint[]argument still resolve to theint[]overload.Open Questions
GetFlattenedIndex(ReadOnlySpan<int>)method itself be made public? It would allow advanced callers to compute flat indices for use withMemoryMarshal.GetArrayDataReference, enabling zero-allocation generic access patterns. This is a more advanced API that could be proposed separately.Related Issues
Prototype
eiriktsarpalis@6fa75b6c4da
NinoFloris commentedon May 23, 2026
@eiriktsarpalis
GetFlattenedIndexwould help us support multi-dimNullable<TEnum>viaNullable<TUnderlying>conversions. Postgres doesn't support jagged arrays, everything 'nested' is multidimensional.Without
GetFlattenedIndexwe'd be duplicating the runtime's row-major stride logic, which is documented at the ECMA-335 level but is the exact kind of code that we don't really want to have to own.As there is no CLR array variance through
Nullable<>we cannot use Array.SetValue/GetValue for these conversions. Without GetFlattenedIndex we have no BCL primitive to do this for multidims: just doingUnsafe.As<int?[,]>on the nullable enum-typed array instance isn't a valid reinterpretation. So the only sound shape is per-element ref-cast starting from the actual array data reference, which is legal for layout-equivalent blittable value types but requires a flat-index to address the slot.Whether
GetFlattenedIndexis exposed or not, the access pattern still goes through ref-byte reinterpretation over an erasedArrayinstance produced byArray.CreateInstanceFromArrayType(AOT compatible, since we don't have per-Nullable<UnknownEnum>conversions rooted). So this doesn't lead to prettier code on our end, but it does create more maintainable code to bridge layout-equivalent multi-dim slot access.bartonjs commentedon Sep 1, 2026
Video
Looks good as proposed.
Add Array.GetValue and SetValue overloads taking ReadOnlySpan<int> (#…