All nonvalue type objects inherit from the Object class, which provides four basic functions. Therefore, all objects have the following four methods: GetHashCode, ReferenceEquals, Equals (==), and ToString.
The GetHashCode method returns a number that will always correspond to the value of an object. This hash code can then be used in collections to drastically reduce the overall number of objects searched for, because you can always look for this number. The collection classes do this by gathering all objects with the same hash code, and then eliminating the rest from the search.
| Note?/td> |
When you call the GetHashCode method on two objects that are equal in value, you should always get the same response. |
It is very common for this class to be overridden, like this:
public override int GetHashCode()
Given two references, ReferenceEquals can tell you if you are working on the same object. This functionality is a lot like comparing the controlling IUnknown in COM. Under the hood, this method just looks at the pointers being used to access the object and compares them. If the objects are the same object, this method returns true; otherwise, it returns false.
The Equals method is used to tell if two objects are the same in value. You will most certainly wish to override this method, because the default functionality is to call ReferenceEquals. This means that, by default, it will compare the objects, not the values of the objects.
public override bool Equals(Object obj)
If you override this method, you will also want to override GetHashCode.
When doing this kind of work, it is common to override the == and != operators as well. In fact, it is recommended that if you override these operators, you also override the Equals method.
public static bool operator == (Object A, Object B) public static bool operator != (Object A, Object B)