So, I've settled on a pattern that I found somewhere on the web to safely override Equals.  I don't remember where I found it, and there are certainly many other good implementations (probably better than mine).

Regardless, I found that I do have a repeating pattern.  I decided to set out to limit this duplication if I could.  Here is what I came up with.

   1: public static bool SafeEquals<T>( this T left, object right, Predicate<T> test )
   2: {
   3:     if( right != null && right.GetType().Equals( left.GetType() ) )
   4:     {
   5:         return test( (T)right );
   6:     }
   7:     return false;
   8: }

This is meant as a utility extension to help me override Equals in my classes without having to write that if condition over and over again.  Also, it takes care of casting to my type as well.

Here is an example of how it is used.  Suppose you have a class that should demonstrate equality if the Key property is equal:

   1: public override bool Equals( object obj )
   2: {
   3:     return this.SafeEquals( obj, test => test.Key == this.Key );
   4: }

or

   1: public override bool Equals( object obj )
   2: {
   3:     return this.SafeEquals( obj, test => object.Equals( test.Key, this.Key ) );
   4: }

Let me know what you guys think.

posted on Saturday, June 28, 2008 10:10 PM
Filed Under [ Agile .Net C# ]

Comments

Gravatar
# re: How To Save Work When Safely Overriding Equals
posted by Will Smith
on 6/29/2008 10:23 PM
I found that style of overriding Equals on MSDN.
http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx
Gravatar
# re: How To Save Work When Safely Overriding Equals
posted by Eddie Velasquez
on 7/7/2008 10:39 AM
You might want to check "left" for null.
Gravatar
# re: How To Save Work When Safely Overriding Equals
posted by Will Smith
on 7/8/2008 10:52 AM
Good point Eddie. In general, this is true. Although my implementation of Equals is safe because it is in the context of a specific instance, it is good practice to avoid exceptions where ever I can.
Gravatar
# re: How To Save Work When Safely Overriding Equals
posted by Sandeep
on 1/12/2011 2:05 AM
Gravatar
# re: How To Save Work When Safely Overriding Equals
on 1/22/2011 9:29 AM
Good point man. in Java correct implementation of equals() is very important to avoid any issue with using them in HashMap.

Thanks
Javin
Why String is immutable in Java

Gravatar
# re: How To Save Work When Safely Overriding Equals
posted by Java Tutorials
on 12/19/2012 8:58 AM
bonus tip for readers: if you override equals, do make sure to override hashcode and compare method accordingly.
Hashcode and Equals contract

Post A Comment
Title:
Name:
Email:
Comment:
Verification: