C# 15 Extension Indexers: Add [ ] to Types You Don't Own
C# 14 let you add properties and methods to types you don't own. C# 15 completes the picture: you can now add square-bracket indexing too.
You've used square brackets since your first lessons: numbers[0] reads the first item of an array or a List<int>. That works because those types declare an indexer, a special member that gives an object [ ] access.
But many types you use every day don't have one, and you can't edit them because they belong to .NET or to someone else's library. In lesson 324 you learned C# 14's extension blocks, which add properties and methods to such types from the outside. The one thing they couldn't add was an indexer. C# 15 removes that gap.
In this lesson, you'll learn how to declare an extension indexer, how to use it, how C# decides between a type's own indexer and yours, and the performance trap to avoid.
What Is It?
The Simple Explanation
An extension indexer is an indexer you declare inside an extension block. Once it's in scope, you can put square brackets after a value of that type as if the type had always had them.
public static class SequenceIndexer
{
extension(IEnumerable<int> sequence)
{
public int this[int index] => sequence.ElementAt(index);
}
}
IEnumerable<int> numbers = Enumerable.Range(1, 10);
int third = numbers[2]; // 3: brackets on an IEnumerable<int>The Technical Definition
Starting with C# 15, an extension block can declare indexers. Because indexers are always instance members, the extension block must name its receiver parameter (here sequence). Extension indexers support the same features as ordinary indexers: get and set accessors, expression-bodied accessors and ref-returning accessors. An indexer declared on the type itself always wins over an extension indexer.
Before C# 15
- Extension blocks could add methods and properties only
- Indexing a type without an indexer meant a method call such as GetAt(2)
- ^1 and ranges only worked if the type had the members built in
With C# 15
- Extension blocks can declare this[...] indexers
- value[2] reads naturally, like a built-in indexer
- Extension Count + indexer + Slice enable ^1, ranges and list patterns
Why Does It Exist?
The Problem — An Incomplete Toolbox
C# 14's extension blocks were designed to let you extend a type with any kind of member. Indexers were left for later, so code that wanted bracket access to a type it didn't own had to fall back to a named method. That made such types feel second-class compared with arrays and lists.
The Solution — Indexers Join Extension Blocks
C# 15 allows this[...] inside an extension block. Combined with extension Count (or Length) properties and an extension Slice method, a type you don't own can now support everything indexing offers: x[i], x[^1], x[1..3] and even list patterns.
Big Picture
How It Works
- If IEnumerable<int> declared its own indexer, that would be used. It doesn't.
- Next the compiler checks whether the type's own Count/Length and indexer can handle the expression. Not here.
- It finds this[int index] in the extension(IEnumerable<int> sequence) block, and numbers becomes the sequence receiver.
- sequence.ElementAt(2) runs and returns 3.
Simple Example
XElement (from System.Xml.Linq) represents a piece of XML. It has no indexer, but reading a child element's text by name is a natural fit for brackets:
using System.Xml.Linq;
XElement product = XElement.Parse(
"<Product><Name>Keyboard</Name><Price>49.99</Price></Product>");
Console.WriteLine(product["Name"]); // Keyboard
Console.WriteLine(product["Price"]); // 49.99
Console.WriteLine(product["Color"] ?? "-"); // - (no such child)
public static class XmlIndexing
{
extension(XElement element)
{
public string? this[string childName] => element.Element(childName)?.Value;
}
}Code → Meaning → Result: product["Name"] calls the extension indexer with element set to product and childName set to "Name". It finds the child element and returns its text, or null when there's no such child.
Real-World Example
Suppose a library you use stores sensor readings in a class that exposes only an array property, with no indexing of its own:
public sealed class Readings(int[] values)
{
public int[] Values { get; } = values;
}You can't change that class, but three extension members give it full indexing support:
Readings readings = new([10, 20, 30, 40]);
Console.WriteLine(readings[^1]); // 40: last item, thanks to Count + indexer
Console.WriteLine(readings[1..3][0]); // 20: a range, thanks to Slice
Console.WriteLine(readings is [10, .., 40]); // True: a list pattern
public static class ReadingExtensions
{
extension(Readings readings)
{
public int Count => readings.Values.Length;
public int this[int index] => readings.Values[index];
public Readings Slice(int start, int length)
=> new(readings.Values.AsSpan(start, length).ToArray());
}
}Count plus the indexer lets C# translate readings[^1] into readings[readings.Count - 1]. Slice lets it translate the range 1..3 into Slice(1, 2). With all three in place, even list patterns from the pattern-matching lessons work on a type that knew nothing about them.
Analogy
You rent a flat and can't knock down walls, but you're allowed to stick numbered hooks onto them. Now you can say "hang the coat on hook 3", as if the wall had been built with hooks.
An extension indexer is that hook rail: you didn't build the type, but you can still give it numbered positions from the outside. If the wall already came with its own hooks (a built-in indexer), people use those first.
Under the Hood
- Lookup order. For x[...] the compiler tries, in order: an indexer declared on the type, built-in index or range support from the type's own members, an extension indexer, and finally index or range support built from extension members. The first one that applies wins.
- A named receiver is required. extension(XElement element) works, but an extension block without a receiver name can't declare an indexer, because an indexer always needs an instance to work on.
- Strings and arrays are excluded. Extension indexers are never used for string or array element access, even if you declare one for those types.
- Some limits. An expression tree (for example a LINQ-to-SQL query in EF Core) can't contain an extension indexer access, and extension Length/Count properties don't take part in collection-expression spread optimizations.
Common Confusion
1. "My extension indexer replaces the built-in one" — no, the built-in one always wins
If a type already has an applicable indexer, C# uses it and ignores yours. Extensions fill gaps; they never override what a type already has.
2. "Extension indexers make any sequence fast to index" — no, the cost is whatever your code does
The IEnumerable<int> example calls ElementAt, which may have to walk through the sequence item by item. The brackets look like array access, but on a plain sequence they can be slow.
3. "I can index a string with my own extension indexer" — no, strings and arrays are excluded
Even if you declare extension(string s) { public char this[Index i] => ...; }, text[...] still uses the string's own indexer. Strings and arrays always use their built-in element access.
Common Mistakes
Mistake 1 — Indexing a slow sequence inside a loop
The mistake: Writing for (int i = 0; i < 10_000; i++) total += sequence[i]; where sequence[i] is an extension indexer that calls ElementAt. For a sequence that isn't a list, every call may start counting from the beginning, so the loop gets slower and slower.
The fix: Loop with foreach instead, or call .ToList() once and index the list. Keep extension indexers for types where looking up a position is genuinely quick.
Mistake 2 — Forgetting to name the receiver
The mistake: Trying to add an indexer to an extension block whose receiver has no name, and getting a compile error.
The fix: Write extension(Readings readings), not just extension(Readings). The indexer's accessors need that name to reach the instance.
When Should I Use It?
- Types you don't own where bracket access reads naturally, such as lookups by name or position in a library type.
- Wrapper types without indexing, where an extension Count + indexer + Slice unlocks ^1, ranges and list patterns.
- Not where the lookup is expensive, because brackets suggest a fast operation. Use a clearly named method instead.
- Not inside EF Core queries, because expression trees can't contain extension indexers.
Mental Model
extension(Type name) { public T this[int i] => ...; } gives value[i].
A built-in indexer always wins; strings and arrays are never extended.
Remember: an extension indexer gives brackets to a type that never had them, but the brackets are only as fast as the code behind them.
Key Takeaway
- C# 15 lets you declare indexers inside C# 14 extension blocks.
- The extension block must name its receiver, for example extension(XElement element).
- Extension indexers support get, set, expression bodies and ref returns, just like ordinary indexers.
- A type's own indexer always takes priority, and string and array element access never uses extension indexers.
- Add an extension Count/Length and Slice to unlock ^1, ranges and list patterns on types you don't own.
Check Your Understanding
Three questions to check the lookup rules and the receiver requirement.
1. Where can you declare an extension indexer in C# 15?
Show answer
Correct: B
Why B is correct: Extension indexers live in the same C# 14 extension blocks as extension properties, and the block needs a named receiver.
Why A is incorrect: There's no extension this[...] syntax. The indexer goes inside an extension block.
Why C is incorrect: If you could edit the type, you'd just add a normal indexer. Extensions exist for types you can't change.
Why D is incorrect: Interfaces can declare indexers for their implementers, but that isn't an extension indexer.
Reinforcement: extension(Type name) { this[...] } = brackets from outside.
2. A type already has its own int indexer, and you also declare an extension indexer with an int parameter for it. Which runs for value[0]?
Show answer
Correct: B
Why B is correct: The compiler tries an indexer declared on the type before any extension indexer. Extensions only fill gaps.
Why A is incorrect: Declaration order doesn't matter. The type's own members always have priority.
Why C is incorrect: Only one indexer is ever chosen for an access.
Why D is incorrect: There's no ambiguity, because the lookup order picks the type's own indexer.
Reinforcement: Built-in first, extension second.
3. Why might sequence[i] inside a big loop be slow when the indexer calls ElementAt?
Show answer
Correct: B
Why B is correct: Brackets look like array access, but the cost is whatever the accessor does. ElementAt on a plain sequence counts items one by one.
Why A is incorrect: An extension indexer over an array or list can be just as fast as a built-in one. It depends on the code inside.
Why C is incorrect: Nothing is recompiled at runtime per call.
Why D is incorrect: Brackets only mean "call the indexer". How fast that is depends entirely on its implementation.
Reinforcement: Fast brackets need fast code behind them.
Your C# 15 tour is nearly complete. The last language feature in this Part is the friendliest one for beginners: labeled break and continue, which finally give nested loops a clean exit.