Skip to content

The indexer of Span (the Item[int index] or this[int index] property) takes an int instead of a uint like the equivalent on an Array. #28070

Closed as not planned

Description

@tarekgh

This causes a lot of code changes when switching from new Foo[20U] to stackalloc Foo[20U]. Since you can't allocate a negative sized array, it seems that this should take a uint, and not an int.

Note

This issue is a copy of the reported issue on the developer community https://developercommunity.visualstudio.com/content/problem/376789/the-indexer-of-span-the-itemint-index-or-thisint-i.html

Activity

  1. tarekgh commented on Dec 6, 2018

    @tarekgh
    MemberAuthor
  2. stephentoub commented on Dec 6, 2018

    @stephentoub
    Member

    takes an int instead of a uint like the equivalent on an Array

    According to the C# spec, the index can be "an expression of type int, uint, long, ulong, or can be implicitly converted to one or more of these types", so it's not that span takes an int instead of a uint, it's that C# allows arrays to be indexed by things other than int as well, and we only have the one overload on span that's int-based.

  3. jkotas commented on Dec 6, 2018

    @jkotas
    Member

    , it's that C# allows arrays to be indexed by things other than int as well

    Correct.

    BTW: The runtime-provided indexer methods on arrays take int indices only as well.

    foreach (var m in typeof(string[]).GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)) Console.WriteLine(m);

  4. mikedn commented on Dec 6, 2018

    @mikedn
    Contributor

    it's that C# allows arrays to be indexed by things other than int as well

    And, for the sake of completeness, the implementation is slightly bugged at that: dotnet/roslyn#30648. Luckily it affects only MD arrays.

    The runtime-provided indexer methods on arrays take int indices only as well.

    That's perhaps not that relevant as IL instructions like ldelem accept both int32 and native int. But then there are no IL instructions to index spans, similar to how there are no IL instructions to index MD arrays.

    Should this issue be moved to csharplang then?

  5. tannergooding commented on Dec 6, 2018

    @tannergooding
    Member

    Should this issue be moved to csharplang then?

    I don't believe so. The issue would likely be closed as non-actionable since this isn't something the language can handle. As you indicated, there is no IL instruction for indexing Span<T> so the compiler relies on the exposed API surface area for functionality like indexing. The only fix here is to expose another indexer that also takes uint or to tell users that they need to explicitly cast to int when indexing.

  6. mikedn commented on Dec 6, 2018

    @mikedn
    Contributor

    I don't believe so. The issue would likely be closed as non-actionable since this isn't something the language can handle.

    I don't think you are in a position to decide what the language can handle or not handle. You didn't even bother to understand the situation and took my side node about IL not having an instruction as evidence that the language can't handle this. Despite obvious evidence that the language already does this for arrays.

  7. tannergooding commented on Dec 6, 2018

    @tannergooding
    Member

    Despite obvious evidence that the language already does this for arrays.

    This is because the language doesn't emit an API call in order to access arrays, they are a built-in/primitive type and are accessed directly via IL instructions.

    Span<T> is not a built-in/primitive type and has no IL instructions that would allow for direct access. The compiler has to emit IL, and for something that doesn't have baked-in support, it has to emit a call to an existing API. It could theoretically add support by baking in knowledge of Span<T> and its internal layout, but there are other problems with that as well (such as ensuring the bounds checks still happen). As has been mentioned by LDM members in the past, all language proposals automatically start out at -100 points and you need 100 points to get them implemented. I don't believe there is any chance that this would happen given the little benefit and that the fix to CoreFX is trivial in comparison.

    I don't think you are in a position to decide what the language can handle or not handle

    I did not decide that this is something the language should not handle. I said that it would likely be closed as non-actionable.

  8. mikedn commented on Dec 6, 2018

    @mikedn
    Contributor

    This is because the language doesn't emit an API call in order to access arrays, they are a built-in/primitive type and are accessed directly via IL instructions.

    I'm not sure what to say. If even after being told that you didn't bother to understand the situation before replying you reply while still not bothering then there is nothing to discuss. I've had quite enough of this already.

  9. tannergooding commented on Dec 6, 2018

    @tannergooding
    Member

    If you are saying you were asking if dotnet/roslyn#30648 should be moved to dotnet/csharplang, that wasn't necessarily immediately clear and this could have been made infinitely simpler by simply stating something along the lines of:

    I meant should dotnet/roslyn#30648 be moved to dotnet/csharplang

    If you are saying it was something else, then I am completely missing it and this would be made simpler if you elaborated rather than leaving people to guess and grab at what you mean if it is obvious there was some form of miscommunication 😄

    • And yes, I could have also made this simpler by asking you to explain what I missed
  10. stephentoub commented on Dec 6, 2018

    @stephentoub
    Member

    I suggest we leave the issue here, since it's not necessarily any more or less language than it is library/runtime, but have a discussion with the C# language design team about it. cc: @MadsTorgersen

    I see three main options:

    1. Do nothing. Developers cast (ideally checked for {u}long) if necessary as they do today.
    2. Add overloads to {ReadOnly}Span<T> for whatever subset of uint, long, and ulong we care to.
    3. Add language support, that would presumably do the equivalent of a cast (checked for {u}long) as it does today for array access.

    My preference is (2), as it eases moving from arrays to spans and limits the knowledge the language needs about spans (it has some knowledge today, but mostly for the more general ref struct concept). We've also already been adding more overloads for the new Range/Index support.

  11. jkotas commented on Dec 6, 2018

    @jkotas
    Member

    Add overloads to {ReadOnly}Span<T> for whatever subset of uint, long, and ulong we care to.

    Would it be meaningful improvement? int indices are very ingrained into the .NET surface. Length property and all other APIs take take or return indices would still return int. Unsigned integers are like unsafe code in .NET - you can use them, but it requires quite a bit of ceremony.

  12. stephentoub commented on Dec 6, 2018

    @stephentoub
    Member

    Would it be meaningful improvement?

    Not a huge one, but I've now heard several folks asking about this. @eerhardt hit up against this the other day with some ML stuff.

  13. mikedn commented on Dec 6, 2018

    @mikedn
    Contributor

    Not a huge one, but I've now heard several folks asking about this. @eerhardt hit up against this the other day with some ML stuff.

    Would be good to have an example. One reason to use uint is due to some potential performance gains. Similar gains could usually be obtained by improvements in the JIT, if a value is used as span/array index the JIT should be able to tell that it is unsigned. As such, it would be a pity to pollute the API because the JIT is having difficulties in keeping up with the needs.

    On the other hand, the fact that array indexing can be done using uint is solely the language's "fault" so it's IMO their problem. Though the prospect of having to make Span<T> an array type or introduce some kind of "array like type" notion into the language spec isn't exactly enticing.

  14. eerhardt commented on Dec 6, 2018

    @eerhardt
    Member

    In case anyone is interested, here is the ML scenario where I hit this problem:

    https://github.com/dotnet/machinelearning/pull/1650/files#diff-2dc3cad0906ef83ce7b8297e32c3b26dR343

                         uint uintSrc = 0;
                         _convertToUInt(in src, ref uintSrc);
                         // Assign to NA if key value is not in valid range.
    -                    if (0 < uintSrc && uintSrc <= _values.Length)
    -                        dst = _values[uintSrc - 1];
    +                    if (0 < uintSrc && uintSrc <= values.Length)
    +                        dst = values[(int)(uintSrc - 1)];
    

    Previously _values was an array. And uintSrc is a uint. ML.NET uses uint here to represent what they call "KeyTypes". More info on KeyTypes.

    So previously, when using an array, I could index into the array using a uint. But now that I converted the code to use ReadOnlySpan, I could no longer index using uint, and was forced to cast.

  15. jkotas commented on Dec 6, 2018

    @jkotas
    Member

    uintSrc <= _values.Length

    Note that this code is equivalent to (long)uintSrc <= (long)_values.Length because of how implicit conversions work in C#. The JIT may be able to optimize out these casts to long in some cases, but they are common performance trap when folks try to use uints to improve performance. You have to sprinkle it with uint casts to avoid this trap, like: if (0 < uintSrc && uintSrc <= (uint)_values.Length)

  16. 7 remaining items

  17. GrabYourPitchforks commented on Feb 15, 2020

    @GrabYourPitchforks
    Member

    So I doubt we are likely to make a traction on this.

    Sure, that's fine. There's already a critical mass behind what we have shipped.

    If we were to introduce some theoretical LongSpan<T> in the future, perhaps we could say that both its Length property and its indexer are typed as nuint, and then the discussion becomes moot? I imagine high-performance code would want to work with a naturally-sized span as often as possible.

  18. markusschaber commented on Feb 17, 2020

    @markusschaber
    3\. Add language support, that would presumably do the equivalent of a cast (checked for {u}long) as it does today for array access.
    

    If we want to avoid baking special kowledge about Span into the Compiler, this could be driven by an attribute which tells the compiler to add checked casts for higher range integer types to a given parameter.

    Having extension method indexers would be another possibility...

  19. GrabYourPitchforks commented on Feb 25, 2020

    @GrabYourPitchforks
    Member

    Just for fun, I experimented with this in a local branch. The Utf8Parser code for parsing integers contains many blocks similar to below.

    if ((uint)index >= (uint)source.Length)
    goto Done;
    num = source[index];
    if (!ParserHelpers.IsDigit(num))
    goto Done;
    index++;
    answer = 10 * answer + num - '0';

    By rewriting this code using nuint (instead of int) as an indexer - and while keeping the code 100% typesafe - we're seeing some fairly good performance improvements. These perf improvements are largely from eliminating the unnecessary movsx instruction that the normal int-based indexer emits.

    Method Toolchain Mean Error StdDev Ratio RatioSD
    TryParseInt32 master 3.069 us 0.0601 us 0.1037 us 1.00 0.00
    TryParseInt32 utf8parser 2.847 us 0.0440 us 0.0390 us 0.91 0.04
  20. apws commented on Sep 12, 2022

    @apws

    I hit this int/uint array/span indexing issue too during work on processor emulator, but probably because I cant figure yet how to place some raw inline array into struct to be able to pin/fix it to obtain damn unsafe pointer for it, instead of safe ref usage and tackling with heap byte array... (want also to share as much code logic in methods/functions possible between C# and C implementation ... quite possible in fact, only some tiny ugly obstacles here)

  21. Genbox commented on Oct 16, 2022

    @Genbox
    Contributor

    The lack of an unsigned indexer for Span makes it exceedingly hard to work with it in interop code. Most win32 APIs work with DWORD (32bit unsigned), so for correctness I usually make a DllImport that matches the signature exactly.

    However, as soon as you need to work with buffers and buffer lengths, you are pretty much forced to use a signed integer for length, as you otherwise can't work with it in C#.

  22. iSazonov commented on Sep 9, 2025

    @iSazonov
    Contributor

    I ran into this problem when I was working with Unicode processing. This is performance-critical code. It's natural to represent Unicode as a uint and use it to index static ReadOnlySpan tables.

    Perhaps the time for a general solution has not yet come, but in my opinion there are enough grounds for the minimal solution. We can use any type for the index - (un)signed byte, (un)signed short and int - one except uint. So why should we abandon it? (This is no worse than using uint for an array.)

  23. tannergooding commented on Sep 9, 2025

    @tannergooding
    Member

    uint is likely to have worse performance because it isn't able to participate in the JIT and other optimizations which are largely oriented around "never negative integers" (that is something constrained to [0, int.MaxValue]). There are a number of additional complexities that come into play when dealing with something that could be in the "full range" ([0, uint.MaxValue]).

    You typically want to be using signed integers here, with idiomatic bounds checking, particularly if it is perf sensitive. In extreme cases one might resort to unsafe code, but such APIs support either signed or unsigned and don't participate in bounds checking or similar (so it is up to the user to ensure safety).

  24. tannergooding commented on Sep 9, 2025

    @tannergooding
    Member

    Noting that a "never negative integer" is a bit different from an "unsigned integer". The more explicit requirement is that the most significant bit must be never set.

  25. iSazonov commented on Sep 10, 2025

    @iSazonov
    Contributor

    @tannergooding If I understood correctly, you're saying that in my Unicode scenario, I can use int to represent a Unicode point. I agree with you on that.

    Also, your reasoning leads us to the conclusion that since this scenario has a rational workaround, it cannot be considered a reason to allow uint to index ReadOnlySpan.

    I can't agree with that. I think just the opposite, you will agree with me that the most important feature of the C# language is strong typing. This means that the application code designer should use the most appropriate types for the domain. Only then he should evaluate whether the type used is redundant.
    So for the Unicode scenario, it will be uint and the second assessment will be whether it is possible to use ushort or byte in this particular code - this is obviously a common and reasonable logical optimization. At a minimum, this gives the compiler additional information for optimizations.

    Only then the designer is forced to think about the limitations of the implementation. But I think you'll agree that it's not normal to perform a constant manual search for optimal type conversion in code. This is understandable when experts use double and even triple casts in this repository for better code generation as a workaround. But you must admit that this is not normal in the general case as well as forced code refactoring during migration to ReadOnlySpan.

    So my Unicode scenario clearly shows that limitations in the implementation of the C# language reduce its value and practical usefulness. And this scenario explicitly asks to allow uint indexing in ReadOnlySpan.

    The same can be said about interop scenario. A DWORD is a uint. There was already more than one tricky bug in interop code when there was a type mismatch.

    In fact, there are infinitely many such scenarios in practice. This is because strong typing is an advantage and designers should take advantage of it.

    The main stopper here was that we tried to look at this problem too broadly. When the world moves from x64 to x128, this will be justified, but for now we could accept a minimal change and allow the uint index in ReadOnlySpan. Why not if it's already there for arrays?

  26. tannergooding commented on Sep 10, 2025

    @tannergooding
    Member

    So for the Unicode scenario, it will be uint

    This is speculative. All the BCL APIs that deal with Unicode deal with int not uint, and so the default type most code dealing with Unicode should have is int. This is furthered by it producing more optimal codegen in key scenarios and it being the "natural" type of operations in C# (any operations on byte, sbyte, short, or ushort all promote to int first as well).

    A user can choose to use uint or ulong, but that comes with limits and a majority of APIs that won't work with them by default without additional casting considerations. This isn't as a reason to "not" add support for uint, but rather as a reason that it is less of a priority.

    A reason "not" is that it can be misleading and lead to unexpected bugs and other problems, such as masking from the user that Span can only represent 2.14b items. For example, if you are doing interop and have a DWORD, then you could happen to have something that contains more (which is unlikely but can happen) that what span can represent. So the chance for failure is more hidden and less obvious when reading the code.

    When the world moves from x64 to x128, this will be justified

    This is unlikely. Unlike the move from 16-bit to 32-bit or 32-bit to 64-bit, where we were actively hitting limits in memory usage and growth for single computer usage indicated a concrete need well in advance, there is no such designators for 64 to 128-bit, in part due to the exponential growth (i.e. 2^32 nanoseconds is 4.295 seconds, while 2^64 nanoseconds is 584.6 years).

    and while the total usage of memory worldwide might be exceeding 64-bits, there are many reasons (involving physical limitations, speed of light, and other nuance) why a single computer (or even compute cluster) won't be exceeding this without some fundamental scientific breakthrough that completely changes how we program and interact with memory in general. At those scales you need to consider memory and the latencies differently such that you don't want "single address space" but rather explicitly want what is functionally "segmented" memory where you first address the machine/segment you want and then the 64-bit address space (or more realistically smaller address space) within that machine.

    Why not if it's already there for arrays?

    It's largely not there for arrays and it only really works due to some quirks that probably wouldn't exist given the hindsight we have. There's a lot of subtle problems that can come about from using these indexers (and not only the example detailed above).

    Having users be explicit about it and not silently risk failure is ultimately better here. It also forces code down a path that is more likely to produce optimal results.

  27. tannergooding commented on Sep 10, 2025

    @tannergooding
    Member

    CC. @jkotas for secondary input, but I'd lean towards closing this as "not planned". I don't think the benefits of a uint indexer on Span<T> outweigh the potential pit of failures or drawbacks. The same goes for nint, which is arguably more useful and has a similar range of pitfalls.

    A user who really wants these can define their own extension indexers providing this support using the C# 14 extension members feature (or in a future version if extension indexers are one of the bits that didn't land this release). The JIT could then recognize and optimize span[(int)someUIntOrNIntValue] if that was deemed worthwhile.

    Users also have the option of unsafe code if it is truly perf critical, although the JIT does the correct and expected thing for the idiomatic code patterns in most cases already (so such unsafe is often not actually required).

  28. jkotas commented on Sep 10, 2025

    @jkotas
    Member

    I'd lean towards closing this as "not planned".

    +1

  29. locked and limited conversation to collaborators on Oct 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions