11.6. The Root of All Classes: ObjectAll C# classes, of any type, ultimately derive from a single class: Object . Object is the base class for all other classes. A base class is the immediate "parent" of a derived class. A derived class can be the base to further derived classes, creating an inheritance tree or hierarchy. A root class is the topmost class in an inheritance hierarchy. In C#, the root class is Object . The nomenclature is a bit confusing until you imagine an upside-down tree, with the root on top and the derived classes below. Thus, the base class is considered to be "above" the derived class. Object provides a number of methods that subclasses can override. These include Equals( ) , which determines if two objects are the same, and ToString( ) , which returns a string to represent the current object. Specifically, ToString( ) returns a string with the name of the class to which the object belongs. Table 11-1 summarizes the methods of Object . Table 11-1. The Object class
In Example 11-4, the Dog class overrides the ToString( ) method inherited from Object , to return the weight of the Dog . Example 11-4. Overriding ToString
Some classes (such as Console ) have methods that expect a string (such as Write-Line( ) ). These methods will call the ToString( ) method on your class if you've overridden the inherited ToString( ) method from Object . This lets you pass a Dog to Console.WriteLine , and the correct information will display. This example also takes advantage of the startling fact that intrinsic types ( int , long , etc.) can also be treated as if they derive from Object , and thus you can call ToString( ) on an int variable! Calling ToString( ) on an intrinsic type returns a string representation of the variable's value. The documentation for Object.ToString( ) reveals its signature: public virtual string ToString( ); It is a public virtual method that returns a string and takes no parameters. All the built-in types, such as int , derive from Object and so can invoke Object 's methods.
If you comment out the overridden function, the base method will be invoked. The base class default behavior is to return a string with the name of the class itself. Thus, the output would be changed to the meaningless: My dog Milo weighs Dog pounds
|