Книга: C# 2008 Programmer

Testing for Equality

Testing for Equality

Consider the following three instances of the Contact class, which implicitly inherits from the System.Object class:

Contact c1 = new Contact() {
 ID = 1234,
 FirstName = "Wei-Meng",
 LastName = "Lee",
 Email = "[email protected]"
};
Contact c2 = new Contact() {
 ID = 1234,
 FirstName = "Wei-Meng",
 LastName = "Lee",
 Email = "[email protected]"
};
Contact c3 = new Contact() {
 ID = 4321,
 FirstName = "Lee",
 LastName = "Wei-Meng",
 Email = "[email protected]"
};

 As you can see, c1 and c2 are identical in data member values, while c3 is different. Now, let's use the following statements to see how the Equals() and ReferenceEquals() methods work:

Console.WriteLine(c1.Equals(c2)); //---False---
Console.WriteLine(c1.Equals(c3)); //---False---
c3 = c1;
Console.WriteLine(c1.Equals(c3)); //---True---
Console.WriteLine(Object.ReferenceEquals(c1, c2)); //---False---
Console.WriteLine(Object.ReferenceEquals(c1, c3)); //---True---

The first statement might be a little surprising to you; did I not just mention that you can use the Equals() method to test for value equality?

Console.WriteLine(c1.Equals(c2)); //---False---

In this case, c1 and c2 have the exact same values for the members, so why does the Equals() method return False in this case? It turns out that the Equals() method must be overridden in the Contact class definition. This is because by itself, the System.Object class does not know how to test for the equality of your custom class; the Equals() method is a virtual method and needs to be overridden in derived classes. By default, the Equals() method tests for reference equality.

The second statement is straightforward, as c1 and c3 are two different objects:

Console.WriteLine(c1.Equals(c3)); //---False---

The third and fourth statements assign c1 to c3, which means that c1 and c3 are now two different variables pointing to the same object. Hence, Equals() returns True:

c3 = c1;
Console.WriteLine(c1.Equals(c3)); //---True---

The fifth and sixth statements test the reference equality of c1 against c2 and then c1 against c3:

Console.WriteLine(Object.ReferenceEquals(c1, c2)); //---False---
Console.WriteLine(Object.ReferenceEquals(c1, c3)); //---True---

If two objects have reference equality, they also have value equality, but the reverse is not necessarily true.

Оглавление книги

Оглавление статьи/книги

Генерация: 1.548. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз