Information Technology Reference
In-Depth Information
if ( Object .ReferenceEquals(left, null ) ||
Object .ReferenceEquals(right, null ))
return false ;
return left.Equals(right);
}
This example code introduces a method I have not discussed yet: namely,
the instance Equals() method. I'll explain that in detail, but I'm not ready
to end my discussion of the static Equals() just yet. For right now, I want
you to understand that static Equals() uses the instance Equals() method
of the left argument to determine whether two objects are equal.
As with ReferenceEquals(), you'll never overload or redefine your own ver-
sion of the static Object.Equals() method because it already does exactly
what it needs to do: determines whether two objects are the same when you
don't know the runtime type. Because the static Equals() method dele-
gates to the left argument's instance Equals(), it uses the rules for that type.
Now you understand why you never need to redefine the static Refer-
enceEquals() and static Equals() methods. It's time to discuss the methods
you will override. But first, let's briefly discuss the mathematical proper-
ties of an equality relation. You need to make sure that your definition and
implementation are consistent with other programmers' expectations.
This means that you need to keep in mind the mathematical properties of
equality: Equality is reflexive, symmetric, and transitive. The reflexive
property means that any object is equal to itself. No matter what type is
involved, a == a is always true. The symmetric property means that order
does not matter: If a == b is true, b == a is also true. If a == b is false, b
== a is also false. The last property is that if a == b and b == c are both
true, then a == c must also be true. That's the transitive property.
Now it's time to discuss the instance Object.Equals() function, including
when and how you override it. You create your own instance version of
Equals() when the default behavior is inconsistent with your type. The
Object.Equals() method uses object identity to determine whether two
variables are equal. The default Object.Equals() function behaves exactly
the same as Object.ReferenceEquals(). But wait—value types are different.
System.ValueType does override Object.Equals(). Remember that ValueType
is the base class for all value types that you create (using the struct key-
word). Two variables of a value type are equal if they are the same type
and they have the same contents. ValueType.Equals() implements that
behavior. Unfortunately, ValueType.Equals() does not have an efficient
 
Search WWH ::




Custom Search