#420 – Laundry List for Implementing Value Equality and IComparable

To implement value equality (equivalence) in a reference type, you should do the following:

  • Override Object.Equals
    • In Object.Equals, call the type-specific Equals method using the as operator
  • Implement IEquatable<T> by adding a type-specific Equals method
    • Check for null using ReferenceEquals method
    • Call base class’ Equals method to compare fields that exist in the base class if it also checks for value equality
    • Check for equivalence by comparing individual fields
  • Override GetHashCode, generating a hash code based on fields used for equivalence
  • Overload == operator
    • Check for 1st parameter being null, compare to 2nd parameter
    • Call 1st parameter’s type-specific Equals method
  • Overload != operator, invoking the == operator
  • Implement IComparable<T>, adding a CompareTo method
    • Check for equivalence using Equals method, then compare individual fields
  • Overload < and > operators
    • Check for 1st parameter being null
    • Call 1st parameter’s CompareTo method
  • Overload <= and >= operators
    • Calculate a result using the <, > and == operators
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

4 Responses to #420 – Laundry List for Implementing Value Equality and IComparable

  1. Peter Chamberlin says:

    Typo: “Equalsmethod” → ‘Equals method’

  2. Peter Chamberlin says:

    Typo: “CompareTomethod” → ‘CompareTo method’

  3. Good summary! I’ve bookmarked this page for future reference.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: