6. The Object class

In C#, every class that you declare has a superclass. If you don't specify a superclass, then the superclass is automatically taken to be Object, a predefined class that is part of the System namespace. (The class Object itself has no superclass.) Thus,

class myClass { . . .

is exactly equivalent to

class myClass : Object { . . .

Every other class is, directly or indirectly, a subclass of Object. This means that any object, belonging to any class whatsoever, can be assigned to a variable of type Object. The class Object represents very general properties that are shared by all objects, belonging to any class. Object is the most abstract class of all!

The Object class actually finds a use in some cases where objects of a very general sort are being manipulated. For example, you can create a list whose data type is List<object> that represents a list of Objects. Since the element type is Object, the list can actually hold more than one type of object.

A program that wants to keep track of various Shapes that have been drawn on the screen can store those shapes in a List. Suppose you create a List<object> listOfShapes. A shape, oneShape, can be added to the end of the list by calling the instance method "listOfShapes.Add(oneShape);". The shape could be removed from the list with "listOfShapes.Remove(oneShape);". The number of shapes in the list is given by the function "listOfShapes.Count". And it is possible to retrieve the i-th object from the list with the function call "listOfShapes[i]". However, note that this method returns an Object, not a Shape. Since you know that the items in the list are, in fact, Shapes and not just Objects, you can type-cast the Object returned by listOfShapes[i] to be a value of type Shape:

oneShape = (Shape)listOfShapes[i];

Let's say, for example, that you want to redraw all the shapes in the list. You could do this with a simple for loop, which is lovely example of object-oriented programming and polymorphism:

         for (int i = 0; i < listOfShapes.Count; i++) {
            Shape s;  // i-th element of the list, considered as a Shape
            s = (Shape)listOfShapes[i];
            s.Redraw();
         }

Or, you could use a foreach loop, and avoid a need for a cast:

         foreach (Shape s in listOfShapes) {
            s.Redraw();
         }