Skip to content

[API Proposal]: Array GetValue SetValue ROS indices #125325

Closed

Description

@NinoFloris

Background and motivation

This would help us to use pooled arrays or fixed size stackallocs, which may not have equal length to the array's rank.

Internally GetFlattenedIndex already uses ROS, so the work would purely be a public api addition.

API Proposal

namespace System;

public class Array
{
    public object? GetValue(params ReadOnlySpan<int> indices);
    public void SetValue(object? value, params ReadOnlySpan<int> indices);
}

API Usage

Array values = ...
var indicesArray = ArrayPool<int>.Shared.Rent(dimensions);
var indices = indicesArray.AsSpan(0, dimensions);
indices.Clear();
do
{
    var value = values.GetValue(indices);
    ...
} (/*increment indices*/);
ArrayPool<int>.Shared.Return(indicesArray);

Note: rent follows return in the same method here. In Npgsql we do have uses across methods (some are async as well), where stackalloc cannot be used.

Alternative Designs

No response

Risks

No response

Activity

  1. added
    api-suggestion
    on Mar 9, 2026
  2. added
    untriaged
    on Mar 9, 2026
  3. dotnet-policy-service commented on Mar 9, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-collections
    See info in area-owners.md if you want to be subscribed.

  4. huoyaoyuan commented on Mar 9, 2026

    @huoyaoyuan
    Member

    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.

  5. NinoFloris commented on Mar 9, 2026

    @NinoFloris
    ContributorAuthor

    We send plenty of reference type arrays as well. These are simple avoidable allocations, and ROS is used internally already.

  6. dotnet-policy-service commented on Mar 9, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-runtime
    See info in area-owners.md if you want to be subscribed.

  7. eiriktsarpalis commented on Mar 9, 2026

    @eiriktsarpalis
    Member

    Background and motivation

    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

    namespace System;
    
    public partial class Array
    {
        // EXISTING
        // public object? GetValue(params int[] indices);
        // public void SetValue(object? value, params int[] indices);
    
        public object? GetValue(params ReadOnlySpan<int> indices);
        public void SetValue(object? value, params ReadOnlySpan<int> indices);
    }

    API Usage

    // Iterating a multi-dimensional array of unknown rank without allocating per-call
    Array values = ...;
    int dimensions = values.Rank;
    var indicesArray = ArrayPool<int>.Shared.Rent(dimensions);
    var indices = indicesArray.AsSpan(0, dimensions);
    indices.Clear();
    do
    {
        var value = values.GetValue(indices);
        // process value
    } while (IncrementIndices(indices, values));
    ArrayPool<int>.Shared.Return(indicesArray);
    // Using stackalloc for a known-rank iteration pattern
    Array values = ...;
    Span<int> indices = stackalloc int[values.Rank];
    indices.Clear();
    do
    {
        var value = 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.

    Related Issues

    Prototype

    eiriktsarpalis@6fa75b6c4da

  8. added
    api-ready-for-review
    and removed
    api-suggestion
    untriaged
    on Mar 9, 2026
  9. added this to the Future milestone on Mar 9, 2026
  10. NinoFloris commented on May 23, 2026

    @NinoFloris
    ContributorAuthor

    @eiriktsarpalis GetFlattenedIndex 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.

  11. bartonjs commented on Sep 1, 2026

    @bartonjs
    Member

    Video

    Looks good as proposed.

    namespace System;
    
    public class Array
    {
        public object? GetValue(params ReadOnlySpan<int> indices);
        public void SetValue(object? value, params ReadOnlySpan<int> indices);
    }
  12. added
    api-approved
    and removed
    api-ready-for-review
    on Sep 1, 2026
  13. added a commit that references this issue on Oct 7, 2026
    b4aec53
  14. locked and limited conversation to collaborators on Nov 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedarea-System.Runtime

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions