Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to override == and != operators when overriding the Equals method? (.NET)

Or it's advisable to do that? Why?

like image 323
Jader Dias Avatar asked Aug 03 '09 12:08

Jader Dias


2 Answers

See the guidelines for overriding Equals() and operator==.

Quote:

By default, the operator == tests for reference equality by determining whether two references indicate the same object. Therefore, reference types do not have to implement operator == in order to gain this functionality. When a type is immutable, that is, the data that is contained in the instance cannot be changed, overloading operator == to compare value equality instead of reference equality can be useful because, as immutable objects, they can be considered the same as long as they have the same value. It is not a good idea to override operator == in non-immutable types.

Basically:

If you want == and != to behave like Equals(..) and !Equals(..) you need to implement the operators. You typically do this only with immutable types.

like image 190
Lasse V. Karlsen Avatar answered Jan 24 '23 06:01

Lasse V. Karlsen


See Guidelines for Implementing Equals and the Equality Operator (==)

For Value Types (structs) "Implement == any time you override the Equals method"

For Reference Types (classes), "Most reference types, even those that implement the Equals method, should not override ==." The exception is for immutable classes and those with value-like semantics.

like image 42
Matt Howells Avatar answered Jan 24 '23 06:01

Matt Howells