Information Technology Reference
In-Depth Information
The output of this code is the following:
x == x is True
x == y is False
Comparison and Equality Operations
When comparing most reference types for equality, only the
references
are compared.
If the references point to the same objects in memory, the equality comparison is
true
;
otherwise it is
false
. This is true even if
the two separate objects
in memory are
exactly
equivalent
in every other respect.
This is ca led a
shallow comparison
.
Figure 8-4 illustrates the comparison of reference types.
On the left of the figure, the references of both
a
and
b
are the same, so a comparison
would return
true
.
On the right of the figure, the references are not the same, so even if the contents of the
two
AClass
objects were exactly the same, the comparison would return
false
.
Figure 8-4.
Comparing reference types for equality
Objects of type
string
are also reference types, but they are compared differently. When
string
s are compared for equality, they are compared in length and content, which is case
sensitive.
f two
string
s have the same length and the same case-sensitive content, the equality
comparison returns
true
, even if they occupy different areas of memory.
This is ca led a
deep comparison
.
Delegates are also reference types, and also use deep comparison. When delegates are
compared for equality, the comparison returns
true
if both delegates are
null
, or if both have
the same number of members in their invocation lists, and the invocation lists match.
When comparing numeric expressions, the types and values are compared.
When comparing
enum
types, the comparisons are done on the underlying values of the
operands.