CHAPTER 6 UNDERSTANDING INHERITANCE AND POLYMORPHISM
In the .NET universe, every type ultimately derives from a base class named System.Object (which
can be represented by the C# object keyword [lowercase “o”]). The Object class defines a set of common
members for every type in the framework. In fact, when you do build a class that does not explicitly
define its parent, the compiler automatically derives your type from Object. If you want to be very clear
in your intentions, you are free to define classes that derive from Object as follows:
// Here we are explicitly deriving from System.Object.
class Car : object
{...}
Like any class, System.Object defines a set of members. In the following formal C# definition, note
that some of these items are declared virtual, which specifies that a given member may be overridden
by a subclass, while others are marked with static (and are therefore called at the class level):
public class Object
{
// Virtual members.
public virtual bool Equals(object obj);
protected virtual void Finalize();
public virtual int GetHashCode();
public virtual string ToString();
// Instance-level, nonvirtual members.
public Type GetType();
protected object MemberwiseClone();
}
// Static members.
public static bool Equals(object objA, object objB);
public static bool ReferenceEquals(object objA, object objB);
Table 6-1 offers a rundown of the functionality provided by some of the methods you’re most likely
to make use of.
Table 6-1. Core Members of System.Object
Instance Method of Object Class
Meaning in Life
Equals()
By default, this method returns true only if the items being
compared refer to the exact same item in memory. Thus,
Equals() is used to compare object references, not the state of
the object. Typically, this method is overridden to return true
only if the objects being compared have the same internal state
values (that is, value-based semantics).
Be aware that if you override Equals(), you should also override
GetHashCode(), as these methods are used internally by
Hashtable types to retrieve subobjects from the container.
Also recall from Chapter 4, that the ValueType class overrides
this method for all structures, so they work with value-based
comparisons.
244