Hi,
I wanted to know when we have the need to override Equal ?
Is it when we use dictionaries ? why ? How does it helps when we access dictionary ?
I could not find any good explanation when I search google.
Can any one explain me this.
Thanks.
Regards
Loading
VulpesPosted Dec 26, 2013, 9:32 AM
1. In the case of reference types, two object references are considered equal if they refer to exactly the same object. Consequently object references which refer to different objects are not considered equal even if all the fields of those objects have exactly the same values.
2. In the case of value types, two instances are considered equal if the corresponding values of all their fields are equal. In order to perform this test, the Equals method needs to use reflection to find out what the fields and their values are.
You might want to override the default behavior of the object.Equals method in the following circumstances.
1. In the case of reference types, you'd prefer equality to be based on field rather than object equality. This is only likely to apply to small immutable classes such as String or Uri in the .NET framework.
2. In the case of value types, you'd prefer to ignore certain fields when testing for equality. An example in the .NET framework is DateTimeOffset which has two fields a DateTime and an offset from UTC. For equality purposes, object.Equals is overridden to ensure that only the DateTime fields have to be the same - the offset field is ignored.
3. In the case of value types, you want to quicken up equality comparisons which, as they are based on reflection by default, tend to be slow.
#2 or #3 mean, in effect, that you should always override object.Equals for structs.
If you override object.Equals, then you should also override the object.GetHashCode method. If you don't do this, then hash-table and dictionary classes which rely on a consistent implementation between the two methods may not work properly.