0Pricing
C# Academy · Lesson

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]); // 5

All lessons in this course

  1. The Index Type and ^ Operator
  2. The Range Type and .. Operator
  3. Ranges with Arrays and Strings
  4. Custom Types Supporting Ranges
← Back to C# Academy