C
C#3y ago
Thinker

What is required for indexing with ranges? [Answered]

What exactly is required for indexing with a range (ex. obj[..3]) to be supported on a class? Just having an indexer public T this[int index] causes a type error because you can't convert between a range and an int. I've know Slice exists and supposedly has something to do with range indexing, but I can't get it to work by just having a public int Slice(int index, int length) method.
7 Replies
Angius
Angius3y ago
Ranges and indices - C# 8.0 draft specifications
This feature specification describes the syntax for ranges and indices, which support indexing individual elements of a sequence or a range of a sequence from the start or end of that sequence.
Thinker
ThinkerOP3y ago
Okay so I have this example code, although it seems that it's calling Slice instead of doing anything with the indexer? Commenting out the Slice method causes a type error.
MODiX
MODiX3y ago
thinker227#5176
sharplab.io (click here)
C c = new();
var x = c[..9];
class C {
public int Count => 99;
public int this[int index] => 0;
public int Slice(int index, int length) => 27;
}
C c = new();
var x = c[..9];
class C {
public int Count => 99;
public int this[int index] => 0;
public int Slice(int index, int length) => 27;
}
React with ❌ to remove this embed.
Thinker
ThinkerOP3y ago
Ohhh that's only for Index, as in [^1]
Thinker
ThinkerOP3y ago
Ranges and indices - C# 8.0 draft specifications
This feature specification describes the syntax for ranges and indices, which support indexing individual elements of a sequence or a range of a sequence from the start or end of that sequence.
Thinker
ThinkerOP3y ago
Okay so Index (ex. [^1]) only requires a int Count or int Length property plus a T this[int] property, while Range (ex. [..3]) requires a int Count or int Length property plus a T Slice(int, int) method.
Accord
Accord3y ago
✅ This post has been marked as answered!

Did you find this page helpful?