In C#, how do you declare an indexer so booking[night] reads and writes a nightly rate, and how does it differ from a property?
answer
- this plus a parameter list
- accessors that take parameters
- overloads by parameter types
- emitted as a property named Item
- no static, no auto-implementation
basics
~10 sDeclare it with this and a parameter list: public decimal this[DateOnly night] { get ...; set ...; }. It is a property whose accessors take parameters: instance-only, overloadable by parameter types and never auto-implemented.
solid answer
~40 s`public decimal this[DateOnly night] { get => _rates[Offset(night)]; set => _rates[Offset(night)] = value; }` makes `booking[night]` call the `get` accessor and `booking[night] = 180m` call the `set` accessor, with `value` holding the new rate. An indexer is a property whose accessors take parameters: they can be of any type, several indexers can coexist when their parameter lists differ, and an `init` accessor or an expression-bodied read-only form works as for properties. The compiler enforces the differences: an indexer must be an instance member (`static` is CS0106), it cannot be auto-implemented (`{ get; set; }` gives CS0501) or use the `field` keyword, and it is emitted as a property named `Item`, so another member called `Item` collides (CS0102) unless `[IndexerName]` renames it. Validate the arguments and throw `ArgumentOutOfRangeException` for a night outside the stay.
code
csharp · 35 linesvar booking = new HotelBooking(new DateOnly(2026, 11, 2), new DateOnly(2026, 11, 5), 140m);
booking[new DateOnly(2026, 11, 3)] = 180m; // set accessor, DateOnly overload
Console.WriteLine(booking[new DateOnly(2026, 11, 3)]); // get accessor, DateOnly overload
Console.WriteLine(booking[0]); // get accessor, int overload
try { _ = booking[new DateOnly(2026, 11, 9)]; }
catch (ArgumentOutOfRangeException ex) { Console.WriteLine($"rejected {ex.ParamName}"); }
public class HotelBooking
{
private readonly decimal[] _rates;
public DateOnly CheckIn { get; }
public HotelBooking(DateOnly checkIn, DateOnly checkOut, decimal baseRate)
{
CheckIn = checkIn;
_rates = Enumerable.Repeat(baseRate, checkOut.DayNumber - checkIn.DayNumber).ToArray();
}
public decimal this[DateOnly night]
{
get => _rates[Offset(night)];
set => _rates[Offset(night)] = value;
}
public decimal this[int nightIndex] => _rates[nightIndex];
private int Offset(DateOnly night)
{
int offset = night.DayNumber - CheckIn.DayNumber;
ArgumentOutOfRangeException.ThrowIfNegative(offset, nameof(night));
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(offset, _rates.Length, nameof(night));
return offset;
}
}go deeper
Recall the this[...] syntax, that get and set accessors receive the indexer's parameters, and that value carries the new element in set.
Explain how indexers differ from properties: instance only, overloadable, never auto-implemented, emitted as a property named Item.
Design indexers that validate their arguments, keep storage private, restrict the setter, and avoid ref-returning indexers unless exposing storage is the point.
Judge whether an indexer or a named lookup method fits the type: indexer syntax suits collection-like types, while a method makes cost and failure modes visible to callers.
## Declaring an indexer An **indexer** lets callers use array-style syntax on an object: `booking[night]`. You declare it with the keyword **`this`** followed by a parameter list in square brackets: - `public decimal this[DateOnly night] { get { ... } set { ... } }` declares a read-write indexer; - inside `set`, the new value arrives in the implicit **`value`** parameter, exactly as in a property setter; - a read-only indexer can be expression-bodied: `public decimal this[int nightIndex] => _rates[nightIndex];`; - the parameters can be of any type and there can be several of them, as in `this[int floor, int room]`; - accessors can have their own access modifiers, and an `init` accessor is allowed as on properties. The indexer does not need to map onto an array. In a hotel booking, a `DateOnly` night can be translated into an offset into a private `decimal[]` of nightly rates, with the class checking that the night falls inside the stay. ## Indexer versus property The C# documentation describes indexers as properties whose accessors take parameters; almost every property rule applies, with these differences: | | Property | Indexer | |---|---|---| | Accessed through | a name: `booking.CheckIn` | an argument list: `booking[night]` | | Static allowed | yes | no (CS0106 "The modifier 'static' is not valid for this item") | | `get` accessor parameters | none | the indexer's parameter list | | Auto-implemented `{ get; set; }` | yes | no (CS0501, the accessor "must declare a body") | | C# 14 `field` keyword | yes | no | | Overloading | no, one per name | yes, by parameter types | ## What the compiler generates An indexer is emitted as an ordinary property named **`Item`**, with `get_Item` and `set_Item` accessor methods that take the indexer's parameters. Two consequences: 1. Declaring another member named `Item` in the same class is error CS0102, "The type already contains a definition for 'Item'". 2. `[System.Runtime.CompilerServices.IndexerName("Rate")]` changes that metadata name, for other .NET languages and for reflection; C# callers keep writing `booking[night]`, and every indexer in the type must use the same name. Overloads work like method overloads: with `this[DateOnly night]` and `this[int nightIndex]` declared, `booking[0]` binds to the `int` indexer at compile time. ## Restrictions to remember - **Not a variable.** Like a property, an indexer is a pair of methods, so `ref booking[night]` is error CS0206 unless the indexer itself returns by `ref`. - **No auto-implementation.** The compiler cannot guess the storage behind an argument list, so every accessor needs a body. - **Instance only.** An indexer always works on a particular object; shared data is exposed through a static method or property instead. - **Validate the arguments.** An out-of-range index is a caller bug: throw `ArgumentOutOfRangeException`, for example through `ArgumentOutOfRangeException.ThrowIfNegative` (.NET 8), rather than returning a made-up rate. ## Designing the booking indexer 1. Index by the domain value callers have (`DateOnly night`), not by an internal offset, and keep the array private. 2. Add an `int` overload only if callers genuinely think in positions, such as "first night". 3. Make the `set` accessor as restrictive as the design allows; a public setter lets any caller rewrite prices. 4. Document which exception an invalid night throws, since the indexer syntax hides that a method runs. Indexers suit types whose purpose is to hold a set of values addressed by a key; when lookup by key is incidental, a named method such as `GetRate(night)` often reads better. ## Indexers in interfaces An interface can declare an indexer too, which is how a pricing component can depend on "something that gives a rate per night" without knowing about `HotelBooking`: - the interface declares only the shape, `decimal this[DateOnly night] { get; }`, with accessors that normally have no body and no modifiers; - the accessors listed decide whether implementers must provide a read-only, write-only or read-write indexer; - a class implements it with an ordinary indexer of the same parameter list, or explicitly as `decimal IRateSource.this[DateOnly night]` when two interfaces declare the same indexer signature. Because an interface cannot hold instance fields, the storage behind an interface indexer always lives in the implementing type, which is the same separation of shape and storage that makes indexers worth using.
- Can you pass booking[night] as a ref argument?Not with an ordinary indexer: it is a pair of accessor methods, not a variable, so `ref booking[night]` is error CS0206, the same rule as for properties. Only a ref-returning indexer such as `public ref decimal this[int i] => ref _rates[i];` hands out a reference, and that exposes the storage the indexer was meant to hide.
- Why does adding a property named Item to a class with an indexer fail to compile?The compiler emits the indexer as a property called `Item`, with `get_Item` and `set_Item` accessors, so a second member named `Item` is a duplicate definition (CS0102). Apply `[IndexerName("Rate")]` from `System.Runtime.CompilerServices` to the indexer to change its metadata name; C# callers still write `booking[night]`.
- An indexer's parameter has to be an int.
- A class can declare only one indexer.
- Indexers can be static, like properties, to index shared data.
- public decimal this[int i] { get; set; } declares an auto-implemented indexer.
- The compiler creates a hidden array to store an indexer's values.