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.