The Root of All Classes: Object
All 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 whether 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
Method | What it does |
|---|---|
| Evaluates whether two objects are equivalent |
| Allows objects to provide their own hash function for use in collections (see Chapter 14) |
| Provides access to the type of the object |
| Provides a string representation of the object |
| Cleans up nonmemory resources; implemented by a finalizer |
In Example 11-4, the Dog class overrides the ToString( ) method inherited from Object, to return the weight of the Dog. You wouldn’t expect to be able to convert ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access