Книга: C# 2008 Programmer

Implementing Equals

Implementing Equals

By default the Equals() method tests for reference equality. To ensure that it tests for value equality rather than reference equality, you need to override the Equals() virtual method.

Using the same Contact class used in the previous section, add the methods highlighted in the following code:

public class Contact {
 public int ID;
 public string FirstName;
 public string LastName;
 public string Email;
 public override bool Equals(object obj) {
  //---check for null obj---
  if (obj == null) return false;
  //---see if obj can be cast to Contact---
  Contact c = obj as Contact;
  if ((System.Object)c == null) return false;
  //---check individual fields---
  return
   (ID == c.ID) && (FirstName == c.FirstName) &&
   (LastName == c.LastName) && (Email == c.Email);
 }
 public bool Equals(Contact c) {
  //---check for null obj---
  if (c == null) return false;
  //---check individual fields---
  return
   (ID == c.ID) && (FirstName == c.FirstName) &&
   (LastName == c.LastName) && (Email == c.Email);
 }
 public override int GetHashCode() {
  return ID;
 }
}

Essentially, you're adding the following:

? The Equals(object obj) method to override the Equals() virtual method in the System.Object class. This method takes in a generic object (System.Object) as argument.

? The Equals(Contact c) method to test for value equality. This method is similar to the first method, but it takes in a Contact object as argument.

? The GetHashCode() method to override the GetHashCode() virtual method in the System.Object class.

The as Keyword

In the Equals(object obj) method you saw the use of the as keyword:

Contact c = obj as Contact;

The as operator performs conversions between compatible types. In this case, it tries to cast the obj object into a Contact object. The as keyword is discussed in detail in Chapter 5.

Notice that the Equals() methods essentially performs the following to determine if two objects are equal in value:

? It checks whether the object passed is in null. If it is, it returns false.

? It checks whether the object passed is a Contact object (the second Equals() method need not check for this). If it isn't, it returns false.

? Last, it checks to see whether the individual members of the passed-in Contact object are of the same value as the members of the current object. Only when all the members have the same values (which members to test are determined by you) does the Equals() method return true. In this case, all the four members' values must be equal to the passed-in Contact object.

The following statement will now print out True:

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

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

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

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