To be able to treat ArraySegment directly like an array, you must cast it to IList with "as". This is described as the proper behavior here:
and here:
Specifically, Microsoft document says:
If you want to retrieve an element by its index in the ArraySegment object, you must cast it to an IList object and retrieve it or modify it by using the IList.Item[Int32] property. The following example retrieves the element in an ArraySegment object that delimits a section of a string array.
What's perplexing is that IList has methods like "Remove" and "RemoveAt". You would expect those to not work on an arraysegment cast as a List. I tested this, and in fact calling Remove throws a runtime error. But the compiler doesn't catch the problem.
I'm surprised that Microsoft considered this acceptable behavior in the design of ArraySegment.
I was trying to brainstorm a wrapper class or some way to hide the List methods that shouldn't be called on the ArraySegment as List. But I couldn't come up with anything.
Does anyone have a suggestion on how to fix this?
EDIT: IReadOnlyList has been suggested instead of IList. IReadOnlyList causes the List to completely read-only, preventing you from modifying the value of elements stored in underlying array. I want to be able to modify the original array values. I just don't want to be able to write list.Remove() or list.Add() since it's clearly wrong and the compiler shouldn't be allowing it.
To anyone who might suggest Span as an alternative:
I am aware of Span, but Span currently has limitations in .NET Framework and Standard. Specifically, it can only be used as a local variable, and thus cannot be passed to other methods.
And to be honest, I actually think Microsoft's IEnumerable heirarchy leaves a bit to be desired -- I can't figure out any way to make an Indexable sequence like List without it offering Add/Remove functionality. ICollection doesn't support Indexing. If anyone has suggestions on that issue itself, I'm all ears.