Custom Types Supporting Ranges
Add Index and Range support to your types.
Two Ways to Support Indices and Ranges
Your own types can opt into Index and Range syntax. There are two recipes: provide explicit indexers, or provide a Length/Count property plus a Slice method.
Explicit Index Indexer
Add an indexer that takes System.Index and the ^ operator just works on your type.
using System;
class Deck {
private int[] cards = { 1, 2, 3, 4, 5 };
public int this[Index i] => cards[i];
}
var d = new Deck();
Console.WriteLine(d[^1]); // 5All lessons in this course
- The Index Type and ^ Operator
- The Range Type and .. Operator
- Ranges with Arrays and Strings
- Custom Types Supporting Ranges