Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 182 ยท Classes and Objects

The object Class: Equals, GetHashCode and ToString

Learn the C# object methods - reference vs value equality, overriding Equals and GetHashCode together, IEquatable<T>, ToString, GetType and MemberwiseClone with runnable examples.

Every type in C# derives from System.Object, written object. That includes classes you write, structs, enums, arrays and even int. Because of that, every value you ever create already has a handful of methods you never wrote: ToString, Equals, GetHashCode, GetType and (internally) MemberwiseClone. Their default behavior is sensible for the runtime but rarely right for your own data types. So you override them, and doing it correctly is one of the places where small mistakes cause large, silent bugs: a dictionary that cannot find a key it just stored, a set that holds duplicates, a test that says two equal objects are different.

This lesson explains the difference between reference equality and value equality, how to override Equals and GetHashCode as a pair, why IEquatable<T> exists, how to write a good ToString, and what GetType and MemberwiseClone do.

Reference equality versus value equality

For a class, the default Equals asks "are these two variables pointing at the same object?" That is reference equality. Two separately created objects holding identical data are different by default.

C# Default equality is by reference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last line prints just Point: the default ToString returns the type name. Most real programs want a.Equals(b) to be true for points with equal coordinates. That is value equality, and for classes you must implement it yourself (structs get a slow reflection-based default, and records generate it for you; see Records).

Strings are the famous example of a class with value equality: new string('a', 1) == "a" is true because string overrides Equals and ==. Arrays and List<T> use reference equality, so two lists with the same items are not equal. Use SequenceEqual to compare their contents.

Overriding Equals

A correct Equals(object? obj) follows a contract. For non-null x, y, z:

  • Reflexive: x.Equals(x) is true.
  • Symmetric: x.Equals(y) equals y.Equals(x).
  • Transitive: if x.Equals(y) and y.Equals(z), then x.Equals(z).
  • Consistent: repeated calls give the same answer while nothing changes.
  • x.Equals(null) is false and must not throw.

The usual shape is: check null, check type, compare the fields.

C# Equals without GetHashCode (a trap)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Equals says True, yet the HashSet and Dictionary cannot find the equal object. Hash-based collections compute GetHashCode() to pick a bucket, and only compare with Equals inside that bucket. The default GetHashCode is based on the object's identity, so the two equal objects land in different buckets. The compiler even warns you: warning CS0659: 'Location' overrides Object.Equals(object o) but does not override Object.GetHashCode(). This warning is the lesson here, so the example keeps it.

The golden rule: override both, consistently

If two objects are equal according to Equals, they must return the same GetHashCode().

The reverse is not required: different objects may share a hash code (a collision), just with a speed penalty. A constant return 1; is legal but turns a dictionary into a linked-list scan. Aim for a hash that spreads values well and uses exactly the fields that Equals compares. HashCode.Combine does this for you:

C# Equals and GetHashCode together, with IEquatable of T

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice the pieces:

  • IEquatable<T> adds bool Equals(T? other). Generic collections (HashSet<T>, Dictionary<TKey,V>, List<T>.Contains) prefer it, which avoids casting and, for structs, avoids boxing. Implement it whenever you override Equals.
  • Equals(object?) delegates to the typed version, so there is one real implementation.
  • HashCode.Combine(a, b, ...) mixes up to eight values into a good hash. For more values use a HashCode instance and call Add.
  • == and != are optional; if you define one, define both. The null-check order matters, so left is null is used rather than left == null, which would recurse forever.
  • The class is sealed, which sidesteps the hard problem of equality across a class hierarchy (should a Place equal a derived NamedPlace?). With records and sealed types the question disappears.

Never put mutable fields into GetHashCode. If you add an object to a HashSet, then change a field that the hash uses, its stored bucket is now wrong and the set can no longer find it. Base equality on immutable data (get; or init; only), or never mutate objects after you put them in a hash-based collection.

Equality for structs and records

A struct gets a default Equals that compares all fields, but it uses reflection in some cases and boxes the argument, so it is slow. For structs that you compare often, implement IEquatable<T> as above, or use a readonly record struct, which does everything for you. A record (class) generates value-based Equals, GetHashCode, ==, != and ToString automatically: that is the fastest way to get correct value equality, covered in Records.

C# A record gets all of this for free

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Writing a good ToString

ToString() returns a human-readable description. The debugger, Console.WriteLine, string interpolation and logging all call it. Rules of thumb:

  • Make it concise and informative: the type's identity or key data, not a dump of everything.
  • Never throw from ToString, and avoid side effects or slow work; debuggers call it constantly.
  • It is for people, not for parsing. If you need a machine format (JSON, CSV), write a separate method. Use IFormattable when callers need format strings (ToString("F2")).
  • Do not include secrets (passwords, tokens) in it, since logs will print them.
C# ToString, and string interpolation calling it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

GetType and typeof

GetType() returns the runtime type of an object as a System.Type. It cannot be overridden. typeof(X) gives the type of a name known at compile time. Comparing them tells you the exact type, ignoring inheritance, while is accepts derived types as well.

C# GetType versus is

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

GetType() is how an Equals override can insist on exactly the same class (GetType() != obj.GetType()), which keeps equality symmetric in unsealed hierarchies.

MemberwiseClone: shallow copies

MemberwiseClone() is a protected method that makes a shallow copy: a new object with every field copied bit for bit. Value-type fields are independent copies, but reference-type fields now point to the same objects as the original. Use it inside your own Clone method.

C# Shallow versus deep copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The original sees Song C because the shallow copy shares the list. Cloning is easy to get wrong; many teams prefer immutable types and with expressions on records, or explicit copy constructors, to the old ICloneable interface (whose Clone() does not even say whether the copy is shallow or deep).

Other members of object

  • static bool ReferenceEquals(object? a, object? b): always the identity test; it ignores overridden Equals and ==.
  • static bool Equals(object? a, object? b): null-safe; calls a.Equals(b). Handy when a may be null.
  • Finalize(): the destructor hook; ignore it until you read about disposal.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the default Equals do for two separately created instances of your own class with identical field values?

    For classes, object.Equals is reference equality: only the same object is equal to itself. Records and strings override it.
  2. 2. What must be true when you override Equals?

    Hash-based collections rely on the rule that equal objects have equal hash codes. Otherwise a HashSet or Dictionary can fail to find an object that is equal.
  3. 3. Why implement IEquatable<T> in addition to overriding Equals(object)?

    Generic collections use IEquatable<T>.Equals(T) when available, which avoids casts and boxing for structs.
  4. 4. What does MemberwiseClone produce?

    It copies each field bit for bit. Value fields are copied, but reference fields are shared with the original.
  5. 5. Which of these is a risk when GetHashCode uses a mutable property?

    The object sits in a bucket chosen from its old hash. After the field changes, lookups use the new hash and miss it.

Summary

  • Every type derives from object; its default Equals compares references for classes, and ToString returns the type name.
  • Override Equals and GetHashCode together, using the same fields; ignoring GetHashCode gives warning CS0659 and breaks hash collections.
  • Implement IEquatable<T>, build the hash with HashCode.Combine, and base equality on immutable data.
  • Records (and readonly record struct) generate correct value equality for you.
  • ToString should be short, safe and for humans; GetType() gives the exact runtime type.
  • MemberwiseClone makes a shallow copy; copy nested references yourself for a deep copy.

Next: Records