.NET 11 Preview - Extension Indexers
[C#, .NET, .NET 11 Preview]
One of the more pivotal features of the .NET platform is the ability to access elements of a collection as a property, using an indexer.
Take the following collection:
List<int> items = [0, 1, 2, 3, 4, 5, 6, 7];
To access the third element, one way to do it is as follows:
var element = items.ElementAt(2);
ElementAt here is a function.
In languages like Java that don’t have properties, this is how you’d do it.
In .NET, there is another way to do it: using a property.
var element = items[2];
This works using a construct called an indexer.
For a long time, indexers have not been available to extension methods.
Suppose we wanted to implement a extension method to IEnumerable<char>, ItemAt, that returns the character at a particular element.
We’d do it like this:
public static class EnumerableExtensions
{
public static char ItemAt(this IEnumerable<char> str, int index)
{
return str.ElementAt(index);
}
}
This we use as follows:
str.ItemAt(0);
It has not been possible to impelment this as a property.
This is now available in .NET 11.
public static class EnumerableExtensions
{
extension(IEnumerable<char> enumerable)
{
public int this[int index] => enumerable.ElementAt(index);
}
}
The magic of the indexer is happening here:
public int this[int index] => enumerable.ElementAt(index);
We would use it like this:
Console.WriteLine((char)str[0]);
This should print the following:

TLDR
In .NET 11, you can now implement property indexers.
The code is in my GitHub.
Happy hacking!