Yippie-Ki-Yay
Yippie-Ki-Yay

Reputation: 22794

C# object comparison

Could someone point out the idea of overloading operator== to perform deep object comparison (instead of reference comparison).

From MSDN:

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.

When would it actually benefit?

And, like, if every object has method Equals, which makes value comparison possible, why would someone ever perform value (not reference) comparison using x == y statement?

I guess I don't understand something, because this looks very weird to me.

Upvotes: 2

Views: 3155

Answers (3)

smartcaveman
smartcaveman

Reputation: 42246

System.String is the classic example of a reference type that benefits from a deep value equality comparison instead of a reference comparison.

In general, there are some circumstances where it makes code easier to write and the meaning of the equality is better expressed by a value comparison than by a reference comparison.

Upvotes: 0

Bala R
Bala R

Reputation: 108937

overloading operator == only improves the readability of your code. Always use .Equals() for the types you define, especially for deep object comparison.

Upvotes: 1

SLaks
SLaks

Reputation: 887225

Overloading the == operator allows you to write x == y, which is much more natural than x.Equals(y), and will work even if x is null.

Upvotes: 6

Related Questions