1.19 — Indexers, Operator Overloading, Conversions¶
← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.18 Tuples, ref, out, in · Next: 1.20 Exceptions
Markers: — · Confidence: 🔴 · Last reviewed: —
TL;DR¶
- An indexer lets your class be used with square brackets:
myThing["key"]. - Operator overloading lets you define what
+,==and so on mean for your type. implicitconversions happen automatically;explicitones need a cast. Useexplicitwhenever the conversion can lose information or fail.
The concept¶
These three features all do the same kind of thing: they let your own type use syntax that normally only works for built-in types.
Used well, they make domain code read naturally — price1 + price2 is clearer than
price1.Add(price2). Used badly, they hide behaviour and confuse readers. The interview
value is mostly in knowing the rules and the risks.
How it works¶
Indexers¶
An indexer is written like a property, but named this and taking parameters:
public class Settings
{
private readonly Dictionary<string, string> _values = new();
public string this[string key]
{
get => _values.TryGetValue(key, out var v) ? v : "";
set => _values[key] = value;
}
}
var settings = new Settings();
settings["theme"] = "dark"; // calls the setter
var theme = settings["theme"]; // calls the getter
Indexers can take any type of parameter, and you can have several overloads:
public Order this[int index] => _orders[index];
public Order? this[Guid id] => _orders.FirstOrDefault(o => o.Id == id);
Operator overloading¶
You define what an operator means for your type using public static operator:
public readonly record struct Money(decimal Amount, string Currency)
{
public static Money operator +(Money a, Money b)
{
if (a.Currency != b.Currency)
throw new InvalidOperationException("Cannot add different currencies");
return a with { Amount = a.Amount + b.Amount };
}
public static Money operator *(Money m, int quantity)
=> m with { Amount = m.Amount * quantity };
public static bool operator >(Money a, Money b) => a.Amount > b.Amount;
public static bool operator <(Money a, Money b) => a.Amount < b.Amount;
}
var total = new Money(10, "GBP") + new Money(5, "GBP"); // Money(15, "GBP")
var bulk = new Money(10, "GBP") * 3; // Money(30, "GBP")
Rules to remember:
- Operators must be
public static. - Some must be declared in pairs:
==with!=,<with>,<=with>=. The compiler enforces this. - If you overload
==, you should also overrideEqualsandGetHashCode, otherwisea == banda.Equals(b)can give different answers — which breaks dictionaries and LINQ in confusing ways. - Some operators cannot be overloaded at all:
&&,||,??,?:,=.
Using a record avoids most of this work, since it generates correct Equals,
GetHashCode and == for you.
Implicit and explicit conversions¶
public readonly record struct Celsius(double Degrees)
{
// IMPLICIT — happens automatically, no cast needed
public static implicit operator double(Celsius c) => c.Degrees;
// EXPLICIT — requires a cast, because it might not be valid
public static explicit operator Celsius(double d) =>
d < -273.15
? throw new ArgumentOutOfRangeException(nameof(d), "Below absolute zero")
: new Celsius(d);
}
Celsius temp = new(20);
double asNumber = temp; // implicit — just works
Celsius back = (Celsius)25.0; // explicit — cast required
Celsius bad = (Celsius)(-300.0); // throws — which is why it is explicit
The rule for choosing: use implicit only when the conversion always succeeds and
loses nothing. If it can throw, lose precision, or surprise the reader, make it
explicit. The cast then acts as a visible warning at the call site.
This mirrors how the built-in types work. int to long is implicit — always safe.
long to int is explicit — it can silently lose data, so you have to ask for it.
Code¶
A realistic strongly-typed ID, which is a common pattern in domain-driven code:
public readonly record struct OrderId(Guid Value)
{
// Implicit OUT is safe — an OrderId always has a valid Guid
public static implicit operator Guid(OrderId id) => id.Value;
// Explicit IN — not every Guid is meant to be an OrderId,
// so make the conversion visible in the code
public static explicit operator OrderId(Guid value) => new(value);
public override string ToString() => Value.ToString();
}
Why bother? Because it stops a whole class of bug:
public void Transfer(OrderId order, CustomerId customer) { }
Transfer(customerId, orderId);
// COMPILE ERROR — the arguments are the wrong way round.
//
// If both were plain Guid, this would compile fine
// and fail mysteriously at runtime.
Two Guid parameters next to each other are very easy to swap by accident. Wrapping them
in distinct types makes the compiler catch it. See
22.8.
Interview questions¶
Q: What is an indexer?
It lets an instance of your class be accessed with square brackets, like an array or a
dictionary. You declare it like a property but name it this and give it parameters. It is
useful when your type genuinely represents a collection or a lookup — a settings class, a
matrix, a custom collection. It is not something to add just because you can; if the type
is not conceptually indexable, a normal named method is clearer.
Q: When should you overload operators?
Only when the operator has an obvious, universally understood meaning for your type.
Adding two Money values or two vectors is natural, and a + b reads better than
a.Add(b). But if a reader has to stop and work out what your + does, you have made the
code worse rather than better. The other important rule is consistency: if you overload
==, you must also override Equals and GetHashCode, otherwise the two ways of
comparing can disagree and things like dictionary lookups start behaving strangely.
Q: What is the difference between an implicit and an explicit conversion operator?
An implicit conversion happens automatically with no cast, so it should only be used when
the conversion always succeeds and never loses information. An explicit conversion requires
a cast at the call site, which acts as a visible signal that something could go wrong. The
built-in types follow the same rule — int to long is implicit because it is always
safe, and long to int is explicit because it can silently truncate.
Traps ⚠️¶
- Overloading
==without overridingEqualsandGetHashCode. Thena == banda.Equals(b)can disagree, and dictionary and LINQ lookups break in ways that are very hard to debug. - Some operators must be declared in pairs.
==/!=,</>,<=/>=. - Implicit conversions that can throw. The cast is the reader's only warning, so removing it removes the warning.
- Overloading operators to mean something unexpected. If
+on your type deletes something, you have created a trap. - Indexers cannot be static, and they cannot be used with the null-conditional operator
on the indexer name itself — though
list?[0]does work. &&and||cannot be overloaded directly. You overload&,|,trueandfalseinstead, which is rarely worth doing.
Related¶
- 1.2 Records — get correct
==andEqualsfor free - 1.9 Polymorphism — operator overloading is compile-time polymorphism
- 22.8 Value objects and strongly-typed IDs — the main real-world use