Alex Rivera | Logout

C# .Equals(), .ReferenceEquals() and == operator

Asked 2010-10-06T05:02:35.593
107

My understanding of these three was:

  • .Equals() tests for data equality (for the lack of a better description). .Equals() can return True for different instances of the same object, and this is the most commonly overridden method.

  • .ReferenceEquals() tests whether or not two objects are the same instance and cannot be overridden.

  • == is the same as the ReferenceEquals() by default, but this CAN be overridden.

But C# station states:

In the object class, the Equals and ReferenceEquals methods are semantically equivalent, except that the ReferenceEquals works only on object instances. The ReferenceEquals method is static.

Now I don't get it. Can anyone shed some light on this?

Edit
Report

2 Answers

28

Have a look at this MSDN article on the subject.

I think the pertinent points are:

To check for reference equality, use ReferenceEquals. To check for value equality, use Equals or Equals.

By default, the operator == tests for reference equality by determining if two references indicate the same object, so reference types do not need to implement operator == in order to gain this functionality. When a type is immutable, meaning the data 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.

Hope this helps!

answered 2010-10-06T05:06:26.333
10

Your understanding of .ReferenceEquals is correct.

.Equals checks data equality for value types, and reference equality for non-value types (general objects).

.Equals can be overridden for objects to perform some form of data equality check

EDIT: Also, .ReferenceEquals can't be used on value types (well it can, but will always be false)

answered 2010-10-06T05:06:12.417

Your Answer