Read the syntax
Expose bracket syntax on your own types while controlling lookup and assignment behaviour.
The later read invokes get for the same position.
What it is and why to use it
A type that represents a sequence or lookup may be clearer with object[index] syntax. An indexer resembles a property with parameters and is declared with this[...]. It can expose read-only or read/write access without making internal storage public. Its behaviour should be predictable for the kind of collection it represents.
How it works
The parameter type determines the supported index, which need not be an integer. get returns the requested value and set receives the incoming value through the value keyword. Indexers can validate bounds or delegate to an underlying collection. Accessing an index does not automatically make an object enumerable; iteration requires a separate contract.
Common mistakes and limitations
Do not hide expensive network calls or surprising mutation behind ordinary-looking bracket syntax. Define missing-key and out-of-range behaviour clearly. An indexer is not a public array field and does not imply a Count property or foreach support.
Run the examples locally
These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.
Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.
C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.
Create and enter a project
dotnet new console -n CSharpExample --framework net10.0
cd CSharpExampleCSharpExample.csproj settings used for these examples
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>12.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>Build and run after saving one example in Program.cs
dotnet build
dotnet run --no-buildContinue learning
Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.
Syntax
public string this[int index] { get => items[index]; set => items[index] = value; }Examples
Wrap a small indexed collection
Expose controlled bracket access while keeping the array private.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
var shelf = new Shelf();
shelf[1] = "C#";
Console.WriteLine(shelf[1]);
class Shelf {
private readonly string[] items = { "PHP", "Java" };
public string this[int index] {
get => items[index];
set => items[index] = value;
}
}
- The assignment invokes the indexer’s set accessor with index 1 and value C#.
- The later read invokes get for the same position.
- The underlying array remains private. This implementation inherits the array’s out-of-range exception behaviour.
- Expected output: C#
- Keep indexed access consistent with the represented data.
Use a string-keyed read-only indexer
Make a missing translation return a clearly defined fallback.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
var labels = new Labels();
Console.WriteLine(labels["save"]);
Console.WriteLine(labels["unknown"]);
class Labels {
private readonly Dictionary<string, string> values = new() { ["save"] = "Save lesson" };
public string this[string key] => values.TryGetValue(key, out var value) ? value : "[missing]";
}
- The indexer accepts a string key rather than a numeric position.
- TryGetValue avoids an exception for an absent key and chooses the documented fallback.
- There is no set accessor, so callers cannot assign through this indexer. The class can still have other methods that mutate its internal map.
- Expected output: Save lesson [missing]
- Keep indexed access consistent with the represented data.
Best practices
- Keep indexed access consistent with the represented data.
- Document missing-key, range and mutation behaviour.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference