Wednesday, January 1, 2014

IEqutable in C#

To do object comparisons you can use Object.Equals method. But this method could behave differently than you expected. Also it will have to do a cast to Object in order to perform the equality comparison which will result in a performance drop.

IEqutable<T> defines a generalized method which a value type or a class can implement to create type specific equality comparison. It contains a single method Equals. The IEqutable<T> interface is used by Collection objects such as Dictionary, List etc. in methods like Contains, IndexOf and Remove. 

When you implement IEquatable, you should implement IEqutable.Equals as well as Object.Equals(Object) method. When you implement IEqutable.Equals, runtime will use this only if you pass object with the same type. Otherwise it'll try to use Object.Equals method.

Using with Value Types
For a value type, you should always implement IEqutable<T> and override Object.Equals(Object) for better performance. Object.Equals boxes value types and relies on reflection to compare two values for equality. See SO answer for an implementation

With value types you also need to overload the equality (==) and inequality (!=) operators which is important to avoid boxing and unboxing in equality checking. You can use ReferenceEquals for this.

IEqutable<T>.Equals method
Indicates whether current object is equal to another object of same type. 

When to use IEqutable<T>

We know that IEqutable<T> is used by generic collections such as Dictionary and List. The IEqutable<T> implementation will require one less cast for  these classes and will be slightly faster than object.Equals method.

Also you can have explicitness of implementing IEqutable<T>


Read this article from CodeProject to get a good understanding

IEqualityComparer<T>
It is an object that performs comparison of two objects of type T. IEqutable<T> is for an object so that it can compare itself with another object. (See difference)

Resources

0 comments:

Post a Comment

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook