SharpRuneOpen playground

C# 15 extension indexers and index-from-end

Add Count and an indexer through an extension block and get readings[^1] for free.

  • 15 min
  • Read, predict, then run
External .NET 11 SDK / stable C# 15. This project does not run in SharpRune's .NET 9 playground.

Read or download the complete SDK project, then follow its setup on your computer. The separate C# companion practice below runs in SharpRune’s .NET 9 console environment.

At a glance

Static helpers here, extension indexer in C# 15

SharpRune sample (.NET 9)
  • ReadingRules.At(readings, 0)
  • Last index written as length minus one
  • ReadingRules.Count(readings)
External project (C# 15)
  • extension(Readings readings) with a named receiver
  • public int this[int index] in the block
  • Extension Count enables readings[^1]
  • Nothing is stored on Readings

Both versions print first:12, last:11 and count:3. Only the external .NET 11 project compiles the extension indexer; C# 14 rejects it with CS9327.

The concept and environment

C# 14 extension blocks added extension properties and methods; C# 15 lets the same blocks declare indexers. Because an indexer is an instance member, the block needs a named receiver parameter. Extension members can also supply what index-from-end access needs: a Count or Length property and an integer indexer. The external .NET 11 project gives a Readings class both through an extension block, so readings[^1] compiles. SharpRune's .NET 9 companion calls ordinary static helpers instead. It compares results; it does not emulate extension binding. Read the environment labels before copying code into the playground.

Walk through the portable program

The companion's Readings stores twelve, fifteen and eleven and exposes them only as a read-only span. ReadingRules.At reads position zero, which is twelve, and the last position, computed as the span length minus one, which is eleven. ReadingRules.Count returns three. Output is first:12, last:11 and count:3. The last-element calculation is written out by hand in the companion; in the external project the compiler performs the same calculation from the ^1 index, using the extension Count property. Both programs read the same three stored values, so any difference in output would point to the indexing rule rather than to the data.

Compile the genuine external feature

In the external project, Readings.cs declares the same class and a ReadingExtensions container with extension(Readings readings). Inside the block, Count is an extension property and this[int index] is an extension indexer. Program.cs uses index zero, index ^1 and the Count property as though Readings declared them. The compiler translates ^1 into Count minus one and calls the extension indexer. The project targets net11.0 with stable language version 15.0; selecting 14.0 instead makes the compiler reject the indexer with CS9327. Save the files together and run the documented project command with a .NET 11 SDK.

Pitfalls and limits

Extension members do not change the Readings type or add storage to it. An indexer or Count declared on the type itself takes precedence, and a missing namespace import makes the extension invisible at the call site. An indexer reads like cheap element access, so keep it cheap: the Microsoft Learn IEnumerable example uses ElementAt, which can walk a sequence from the start on every call. Index-from-end needs Count or Length plus an integer indexer; range syntax additionally needs a Slice method. Document which of these members a consumer can rely on.

Practice one: isolate a contract

First, add a second-to-last lookup, readings[^2], in the external project and the equivalent length-minus-two helper call in the companion. Predict fifteen in both. Hint: compute the expected value from the data, not from either implementation, so an off-by-one mistake in one version is visible. Then pass an index of three to both versions and confirm that each throws IndexOutOfRangeException from the span; the extension indexer adds no bounds checking or error message of its own. Decide whether callers should receive a clearer exception, and add it to both versions if they should.

Practice two: challenge an assumption

For another exercise, add a Slice(int start, int length) extension method that returns a new Readings built from the span, and use readings[1..] in the external project. Predict a Readings holding fifteen and eleven. Hint: range access uses Count and Slice, so print the slice's Count and first element rather than the object itself. Write the companion version as an explicit helper call. Do not add a runtime registry to imitate extension lookup; the compiler resolves these members statically, at each call site.

Review the resulting contract

Review an extension indexer like any other indexer: it should be predictable, cheap and free of surprising effects. The extension form lets a library add indexing to a type it does not own, and supplying Count enables index-from-end syntax without changing that type. The external project demonstrates the genuine C# 15 binding, alongside the C# 14 extension property it builds on. The portable companion keeps the same element rules inspectable in SharpRune, using explicit helper calls instead of the new syntax. Neither version should be presented as the other.

External .NET 11 SDK / stable C# 15. This project does not run in SharpRune's .NET 9 playground.

C# 15 extension indexers and index-from-end lab

Set up the SDK project

  1. Save every listed file at its exact relative path in a fresh directory.
  2. Install a .NET 11 SDK supporting stable C# 15; check dotnet --version.
  3. Run dotnet run --project FeatureLab.csproj. Keep this external code separate from the .NET 9 playground.

Download complete SDK project ↗

Project files

Program.csDownload file ↗
Program.cs
var readings = new Readings(12, 15, 11);
Console.WriteLine($"first:{readings[0]}");
Console.WriteLine($"last:{readings[^1]}");
Console.WriteLine($"count:{readings.Count}");
Readings.csDownload file ↗
Readings.cs
public sealed class Readings(params int[] values)
{
    public ReadOnlySpan<int> AsSpan() => values;
}

public static class ReadingExtensions
{
    extension(Readings readings)
    {
        public int Count => readings.AsSpan().Length;
        public int this[int index] => readings.AsSpan()[index];
    }
}
FeatureLab.csprojDownload file ↗
FeatureLab.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <LangVersion>15.0</LangVersion>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>

Expected result

Expected console output, in this order: first:12 last:11 count:3 The portable companion compares the same small rule using older syntax; it does not compile or emulate the new feature.

Use the listed SDK and dependencies for this project. Open C# practice runs the separate portable exercise.

C# companion practice

Program.cs
using System;
var readings = new Readings(12, 15, 11);
Console.WriteLine($"first:{ReadingRules.At(readings, 0)}");
Console.WriteLine($"last:{ReadingRules.At(readings, readings.AsSpan().Length - 1)}");
Console.WriteLine($"count:{ReadingRules.Count(readings)}");
sealed class Readings(params int[] values)
{
    public ReadOnlySpan<int> AsSpan() => values;
}
static class ReadingRules
{
    public static int Count(Readings readings) => readings.AsSpan().Length;
    public static int At(Readings readings, int index) => readings.AsSpan()[index];
}
Open C# practice

C# practice output

first:12
last:11
count:3
Try this
The companion computes length minus one by hand. In the external project the compiler derives ^1 from the extension Count and indexer.

Further reading