.Net Tips — always override ValueType.Equals

You should already know that in C# all types derive from System.Object and that C# sup­ports both ref­er­ence types (which are allo­cat­ed onto the heap) as well as val­ue types (prim­i­tives, enum, struct, etc. which are allo­cat­ed onto the stack).

One of the key dif­fer­ences between val­ue types and ref­er­ences types is that when you pass a ref­er­ence type around the ref­er­ence (essen­tial­ly a 32-bit inte­ger which ref­er­ences a loca­tion in the heap where the actu­al object is stored) is copied not the object but when you pass a val­ue type around a clone of the object is cre­at­ed and returned instead.

In terms of equal­i­ty com­par­i­son this means ref­er­ence com­par­i­son will ALWAYS fail for two val­ue type objects, and for this rea­son, the base class of all val­ue types – Val­ue­Type – over­rides the vir­tu­al Object.Equals method to com­pare all mem­ber vari­ables in a derived type rather than the ref­er­ence.

Override the default Equals method

With­out know­ing the run­time names and types of the mem­ber vari­ables, the default imple­men­ta­tion of ValueType.Equals relies on the use of reflec­tion and reflec­tion as we all know, is slow. As a gen­er­al rule of thumb, it’s rec­om­mend­ed that you ALWAYS over­ride the ValueType.Equals method when cre­at­ing your cus­tom val­ue type and you should strong­ly con­sid­er over­load­ing the == and != oper­a­tors too whilst you’re at it!

Liked this post? Why not support me on Patreon and help me get rid of the ads!