Other

Equality in C#: reference, value and operator semantics

Nick Cosentino (Dev Leader)
Other

Equality in C# is not one operation: ==, Equals and ReferenceEquals answer different questions. This article shows how the compile-time operand types pick the operator, with examples spanning strings, records, structs and boxing.

Key points

  • Two statically string operands compare contents with ==; declaring them as object switches to reference comparison.
  • object.Equals returns true for two nulls, false for one, and skips the override for identical references.
  • ReferenceEquals always asks the identity question and is never redirected to an overloaded == operator.
  • A plain class uses reference equality for ==; record classes and record structs get generated value-equality operators.
  • An ordinary struct can inherit Equals behavior but will not compile with == unless it declares an operator.
  • Record equality follows each component's own contract, so array or list members are not compared deeply.
  • Boxing preserves the value but creates a distinct object; a boxed int and boxed long are not equal under object.Equals.

Real-world use

  • An API boundary where a caller receives values through object, an interface or a base class, changing which operator is selected.
  • Record-based value objects holding arrays or mutable references, where generated equality may not match the expected result.
  • Domain entity comparisons where identity and content questions are easily confused and the wrong operation is picked.
  • Null checks that should use a null pattern instead of an overloaded == operator.

This summary was generated by the agent from the original post on Nick Cosentino (Dev Leader). The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message