Information Technology Reference
In-Depth Information
implementation. ValueType.Equals() is the base class for all value types.
To p r o v i d e t h e c o r r e c t b e h a v i o r, i t m u s t c o m p a r e a l l t h e m e m b e r v a r i a b l e s
in any derived type, without knowing the runtime type of the object. In
C#, that means using reflection. As you'll see in Item 43, there are many
disadvantages to reflection, especially when performance is a goal. Equal-
ity is one of those fundamental constructs that gets called frequently in
programs, so performance is a worthy goal. Under almost all circum-
stances, you can write a much faster override of Equals() for any value
type. The recommendation for value types is simple: Always create an
override of ValueType.Equals() whenever you create a value type.
Yo u s h o u l d o v e r r i d e t h e i n s t a n c e E q u a l s ( ) f u n c t i o n o n l y w h e n y o u w a n t
to change the defined semantics for a reference type. A number of classes
in the .NET Framework Class Library use value semantics instead of ref-
erence semantics for equality. Two string objects are equal if they contain
the same contents. Two DataRowView objects are equal if they refer to the
same DataRow. The point is that if your type should follow value seman-
tics (comparing contents) instead of reference semantics (comparing
object identity), you should write your own override of instance
Object.Equals().
Now that you know when to write your own override of Object.Equals(),
you must understand how you should implement it. The equality rela-
tionship for value types has many implications for boxing and is discussed
in Item 45. For reference types, your instance method needs to follow pre-
defined behavior to avoid strange surprises for users of your class. When-
ever you override Equals(), you'll want to implement IEquatable<T> for
that type. I'll explain why a little further into this item. Here is the standard
pattern for overriding System.Object.Equals. The highlight shows the
changes to implement IEquatable<T>.
public class Foo : IEquatable < Foo >
{
public override bool Equals( object right)
{
// check null:
// this pointer is never null in C# methods.
if ( object .ReferenceEquals(right, null ))
return false ;
if ( object .ReferenceEquals( this , right))
return true ;
 
Search WWH ::




Custom Search