Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/forums/c-sharp/)
-   -   Make Types Equatable (http://www.go4expert.com/forums/make-types-equatable-t21336/)

arunlalds 13Mar2010 15:06

Make Types Equatable
 
You should override Object.Equals() and also implement the
IEquatable<T> interface.
By default, Equals() on a reference type checks to see if the objects refer to the same
location in memory. This may be acceptable in some circumstances, but often, you’ll
want to provide your own behavior. With value types, the default behavior is to reflect
over each field and do a bit-by-bit comparison. This can have a very negative impact
on performance, and in nearly every case you should provide your own implementation
of Equals().
Code:

struct Vertex3d : IFormattable, IEquatable<Vertex3d>
{
...
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (obj.GetType() != this.GetType())
return false;
return Equals((Vertex3d)obj);
}
public bool Equals(Vertex3d other)
{
/* If Vertex3d were a reference type you would also need:
* if ((object)other == null)
* return false;
*
* if (!base.Equals(other))
* return false;
*/
return this._x == other._x
&& this._y == other._y
&& this._z == other._z;
}
}

Pay special attention to the note in Equals(Vertex3d other). If Vertex3d
was a reference type and other was null, the type-safe version of the function would
be called, not the Object version. You also need to call all the base classes in the
hierarchy so they have an opportunity to check their own fields.
There’s nothing stopping you from also implementing IEquatable<string> (or any
other type) on your type—you can define it however you want. Use with caution,
however, because this may confuse people who have to use your code.


All times are GMT +5.5. The time now is 08:36.