liveBook · Manning

Operator overloading

As explained in .NET in Action, Second Edition

Operator overloading is a language feature that lets a type define the behavior of an operator for its values.

Operator overloading lets a type define what an operator means for its values. In C#, subtracting two DateTime values invokes DateTime's overloaded subtraction operator and returns a TimeSpan. section 7.1

Elapsed time in a stopwatch

A stopwatch calculates elapsed time with `_stopTime - _startTime`. Although both operands are structs rather than numbers, the overloaded operator computes the difference from their tick counts and constructs a TimeSpan. section 7.1

public static TimeSpan
  operator -(DateTime d1, DateTime d2)       #1
  => new TimeSpan(d1.Ticks - d2.Ticks);      #2

The operator declaration makes the runtime behavior explicit: subtraction accepts two DateTime values and returns a TimeSpan built from their tick difference. section 7.1

The example also exposes practical testing concerns around time-dependent operators:

  • Using DateTime.UtcNow directly forces tests to depend on real elapsed time, making sleep-based tests slow and flaky. section 7.1

How .NET in Action, Second Edition covers it

How deep it goes
Defines the feature and shows its DateTime-to-TimeSpan implementation, without surveying general operator-design rules.
Examples
Uses stopwatch elapsed-time code, an explicit DateTime subtraction operator, and a clock-controlled restart test.
What you can do after
Understand how overloaded subtraction produces TimeSpan values and how clock injection makes related tests deterministic.
How it connects
Connects DateTime, DateTimeOffset, TimeSpan, structs, dependency injection, and deterministic testing.

Also explained in

Compare how 2 books explain operator overloading →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.