Information Technology Reference
In-Depth Information
Let's start with the two functions you should never change. Object
.ReferenceEquals() returns true if two variables refer to the same object—
that is, the two variables have the same object identity. Whether the types
being compared are reference types or value types, this method always tests
object identity, not object contents. Yes, that means that ReferenceEquals()
always returns false when you use it to test equality for value types. Even
when you compare a value type to itself, ReferenceEquals() returns false.
This is due to boxing, which is covered in Item 45.
int i = 5 ;
int j = 5 ;
if ( Object .ReferenceEquals(i, j))
Console .WriteLine( "Never happens." );
else
Console .WriteLine( "Always happens." );
if ( Object .ReferenceEquals(i, i))
Console .WriteLine( "Never happens." );
else
Console .WriteLine( "Always happens." );
Yo u ' l l n e v e r r e d e fi n e O b j e c t . R e f e r e n c e E q u a l s ( ) b e c a u s e i t d o e s e x a c t l y w h a t
it is supposed to do: tests the object identity of two different variables.
The second function you'll never redefine is static Object.Equals(). This
method tests whether two variables are equal when you don't know the
runtime type of the two arguments. Remember that System.Object is the
ultimate base class for everything in C#. Anytime you compare two vari-
ables, they are instances of System.Object. Value types and reference types
are instances of System.Object. So how does this method test the equality
of two variables, without knowing their type, when equality changes its
meaning depending on the type? The answer is simple: This method del-
egates that responsibility to one of the types in question. The static
Object.Equals() method is implemented something like this:
public static new bool Equals( object left, object right)
{
// Check object identity
if ( Object .ReferenceEquals(left, right) )
return true ;
// both null references handled above
 
Search WWH ::




Custom Search