#408 – Overloading the == Operator for a Reference Type

You can override the Equals method for a type to implement value equality for the type. You can also overload the == operator.

By default, the == operator will do a reference equality check, only returning true if two references point to exactly the same object.  This is normally what you want for a reference type, using the Equals method if you want to check for value equality.  But there might be cases when you want to also overload the == operator, having it also check for value equality.  You might do this if your type represents some basic value, like a complex number.

Some guidelines.  Whenever you overload the == operator, you should also:

  • Overload != operator
  • Override Equals method
  • Overload < and > operators

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #408 – Overloading the == Operator for a Reference Type

  1. Pingback: #412 – Guidelines when Overloading == Operator for a Value Type « 2,000 Things You Should Know About C#

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers