1.6.14 Equality vs Identity

Matching Values Can Belong to Different Objects

Two Players can both have the name Jordan while remaining two separate objects. Their names match; their objects do not have the same identity.

Two references reach separate Players who share the name Jordan.
Initial relationship
  • New
  • Changed
  • Removed
Equality Asks About Values

The expression `first.Name == second.Name` compares two names. It can be true even when `first` and `second` refer to different Players.

Identity Asks Which Object

Identity means that two references reach the same object. C# can ask this question directly for class references:

object.ReferenceEquals(first, second)

Two separately created Players make this expression false. If `Player alias = first;`, comparing `first` and `alias` makes it true.

First and alias both refer to the same Player object.
How the relationship changes
  • New
  • Changed
  • Removed
Matching Names Do Not Merge Objects

Assigning `second.Name = first.Name` makes the names match. It does not turn the Players into one object. Each still has its own fields and can change independently.

An Alias Shares Identity

Assigning `Player alias = first;` makes `alias` another path to the first Player. A field change through either path is visible through the other.