1

A BinaryInteger<T> is an integer of some bit-length. I'd like to use it to index an array.

Casting to an int isn't possible - I have to use int.CreateTruncating(i) (or similar) at run-time to get an array index.

Is there a way to get array[] to accept an IBinaryInteger<T> as an index?

I know I could use a dictionary or similar but array has some other neat operations I'd like to use as well, like AsSpan, CopyTo, etc.

I'm on .NET 9.

14
  • 5
    no, there is no way, many array's features are possible only because they work with int indexes, for any other types - dictionary Commented 2 days ago
  • 3
    Why are you trying to do this? Maybe there is a better solution. Commented 2 days ago
  • 1
    Remember the history here: IBinaryInteger<T> et. al. are more than 20 years newer than the definition of System.Array, and something like 18 years newer than the interfaces in System.Collections.Generic. Going back and changing APIs who break a lot of code... Commented 2 days ago
  • 7
    Why can't you just use int.CreateTruncating(i)? Commented 2 days ago
  • 1
    What are you really trying to do? You could add an extension method that does whatever you want to do, and in c# 14 you should be able to add an indexer with the "extension member" feature. But you will need to do some kind of conversion eventually. Keep in mind that you probably want to avoid boxing by using generic parameters with constraints, so that the generated code just produces a simple cast, or no cast at all if the type already is int. Commented 2 days ago

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.