tags:

views:

72

answers:

1

.NET contains its own equality comparison functionality, however I don't really understand how it works.

If the desired Equals() and == behaviour is to verify that every field of an object is equal to every field of another object, is it necessary to override Equals() with a method that does this explicitly?

+5  A: 

If you're working with a class, then yes, it's necessary.

With reference types (classes), .NET, by default, provides an equality comparison that compares the reference itself, not values within the class. Overriding Equals is required if you want a field-by-field comparison.

With structs (value types), the default comparison is to compare field-by-field.

From the documentation:

The default implementation of Equals supports reference equality for reference types, and bitwise equality for value types. Reference equality means the object references that are compared refer to the same object. Bitwise equality means the objects that are compared have the same binary representation.

Reed Copsey
As the documentation suggests, bitwise isn't exactly "field-by-field" - if I have a struct that contains a reference type, the default Equals() will use reference equality even if the referenced type overrides Equals().
dahlbyk
It's probably worth noting, as well, that if you override `Equals`, you should typically override `GetHashCode()`, as well.
Nathan Ernst
@ Nathan Ernst - +1 for you point.
Ram