CHAPTER 6 UNDERSTANDING INHERITANCE AND POLYMORPHISM
Finalize()
For the time being, you can understand this method (when
overridden) is called to free any allocated resources before the
object is destroyed. I talk more about the CLR garbage collection
services in Chapter 9.
GetHashCode()
This method returns an int that identifies a specific object
instance.
ToString()
This method returns a string representation of this object, using
the . format (termed the fully qualified
name). This method will often be overridden by a subclass to
return a tokenized string of name/value pairs that represent the
object’s internal state, rather than its fully qualified name.
GetType()
This method returns a Type object that fully describes the object
you are currently referencing. In short, this is a Runtime Type
Identification (RTTI) method available to all objects (discussed
in greater detail in Chapter 15).
MemberwiseClone()
This method exists to return a member-by-member copy of the
current object, which is often used when cloning an object (see
Chapter 8).
To illustrate some of the default behavior provided by the Object base class, create a final C#
Console Application named ObjectOverrides. Insert a new C# class type that contains the following
empty class definition for a type named Person:
// Remember! Person extends Object.
class Person {}
Now, update your Main() method to interact with the inherited members of System.Object as
follows:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with System.Object *****\n");
Person p1 = new Person();
// Use inherited members of System.Object.
Console.WriteLine("ToString: {0}", p1.ToString());
Console.WriteLine("Hash code: {0}", p1.GetHashCode());
Console.WriteLine("Type: {0}", p1.GetType());
// Make some other references to p1.
Person p2 = p1;
object o = p2;
245