Operators and indexers

An overloaded operator

A type may define what + means for two of its values, as long as at least one operand is the type itself. The operator is a static method named op_Addition in the assembly and written with the keyword operator in the source:

var first = new Money(10m, "EUR"); var second = new Money(2.50m, "EUR"); var sum = first + second; Console.WriteLine(sum); Console.WriteLine($"equal {first == new Money(10m, "EUR")}"); Console.WriteLine($"different {first != second}"); readonly struct Money : IEquatable<Money> { public Money(decimal amount, string currency) { Amount = amount; Currency = currency; } public decimal Amount { get; } public string Currency { get; } public static Money operator +(Money left, Money right) => new(left.Amount + right.Amount, left.Currency); public static bool operator ==(Money left, Money right) => left.Equals(right); public static bool operator !=(Money left, Money right) => !left.Equals(right); public bool Equals(Money other) => Amount == other.Amount && Currency == other.Currency; public override bool Equals(object? obj) => obj is Money other && Equals(other); public override int GetHashCode() => HashCode.Combine(Amount, Currency); public override string ToString() => $"{Amount:F2} {Currency}"; }

dotnet run

12.50 EUR
equal True
different True

first + second reads like arithmetic and returned a new value with the sum and the currency of the left operand. The currency is not checked, which is the kind of decision the operator makes: adding two currencies would be a bug, and a stricter version would throw or return a result type.

== and IEquatable

Defining == is a package of four members, and the compiler checks that the pairs match:

HashCode.Combine builds the hash from the two fields without a hand-written formula. The equality is the one the first program used for equal True.

implicit and explicit conversion

A type may also decide how it converts to and from another type. implicit means the conversion may happen without a cast, explicit means the reader must write one:

Money price = 12.5m; decimal raw = (decimal)price; Console.WriteLine(price); Console.WriteLine(raw); Console.WriteLine($"type {price.GetType().Name}"); readonly struct Money { public Money(decimal amount) => Amount = amount; public decimal Amount { get; } public static implicit operator Money(decimal amount) => new(amount); public static explicit operator decimal(Money money) => money.Amount; public override string ToString() => $"{Amount:F2}"; }

dotnet run

12.50
12.5
type Money

The first line took a decimal without a cast because the conversion is implicit; the second needed the cast because it is explicit. The two prints differ because ToString of the type formats with two decimals and the plain decimal keeps its own scale. An implicit conversion that loses information, from a wide type to a narrow one, is a bug in the making; that is the case for explicit.

An indexer

An indexer is a property named this with parameters, so a class can be indexed like an array or a dictionary. The getter and the setter are ordinary code, which is where a default for a missing key belongs:

var temps = new Temperatures(); temps["Kyiv"] = 7; temps["Lima"] = 24; Console.WriteLine($"Kyiv {temps["Kyiv"]}"); Console.WriteLine($"Oslo {temps["Oslo"]}"); Console.WriteLine($"count {temps.Count}"); class Temperatures { private readonly Dictionary<string, int> values = new(); public int this[string city] { get => values.TryGetValue(city, out var value) ? value : -99; set => values[city] = value; } public int Count => values.Count; }

dotnet run

Kyiv 7
Oslo -99
count 2

A missing city returned -99 and did not add a key: the count stayed two. A real type would throw KeyNotFoundException or return int?, and that choice is the whole design of the indexer. Several parameters are allowed, so a matrix reads as grid[row, column].

Exercises

  1. Add - and a * by a decimal to Money.
  2. Make Money + Money refuse two different currencies and read the exception.
  3. Remove the explicit decimal cast in the second program and read the error.
  4. Give Temperatures a second indexer with two parameters, a city and a month.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does an operator overload compile to?

    Answer

    A static method named op_Addition or a similar special name

    The C# keyword maps to a static method with a reserved name in the assembly.

  2. Which members must be defined together with ==?

    Answer

    != , Equals and GetHashCode

    The pair of operators is required, and equality must agree with Equals and the hash code.

  3. What does this program print? var a = new P(1); var b = new P(1); Console.WriteLine(a == b); readonly struct P(int n) { public int N { get; } = n; public static bool operator ==(P x, P y) => x.N == y.N; public static bool operator !=(P x, P y) => x.N != y.N; public override bool Equals(object? o) => o is P p && p.N == N; public override int GetHashCode() => N; }

    Answer

    True

    The operator compares the single field, and both values hold one.

  4. What does an implicit conversion allow?

    Answer

    The conversion without a cast at the call site

    implicit means the compiler may insert the conversion; explicit needs the cast written out.

  5. What is an indexer?

    Answer

    A property named this with parameters

    The this keyword with a parameter list declares the get and set pair used by the brackets.

  6. What does this program print? var t = new T(); t["a"] = 5; Console.WriteLine(t["a"] + t["b"]); class T { private readonly Dictionary<string, int> d = new(); public int this[string k] { get => d.TryGetValue(k, out var v) ? v : 0; set => d[k] = value; } }

    Answer

    5

    The missing key gives 0 and the stored one gives 5, so the sum is 5.

  7. Why must GetHashCode agree with ==?

    Answer

    A dictionary finds a key by its hash, so equal values need equal hashes

    A mismatch makes a key that is present unreachable in a hash-based collection.

  8. Which conversion should be explicit?

    Answer

    One that can lose information

    A lossy conversion is a decision the reader should see written as a cast.

  9. What does this program print? var m = new Money(3m); Console.WriteLine(m + m); readonly struct Money(decimal amount) { public decimal Amount { get; } = amount; public static Money operator +(Money a, Money b) => new(a.Amount + b.Amount); public override string ToString() => Amount.ToString("F1"); }

    Answer

    6.0

    The operator adds the two amounts and ToString formats the total with one decimal.

  10. What does CS0216 report?

    Answer

    An operator was defined without its required pair

    Defining == without != or the other way round is the usual case of that error.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image