The object Type

object (System.Object) is the ultimate base class for all types. Any type can be implicitly upcast to object.

To illustrate how this is useful, consider a general-purpose stack. A stack is a data structure based on the principle of “last in, first out” (LIFO). A stack has two operations: push an object on the stack, and pop an object off the stack. Here is a simple implementation that can hold up to 10 objects:

public class Stack
{
  int position;
  object[] data = new object[10];
  public void Push (object o) { data[position++] = o; }
  public object Pop() { return data[--position]; }
}

Because Stack works with the object type, we can Push and Pop instances of any type to and from the Stack:

Stack stack = new Stack();
stack.Push ("sausage");
string s = (string) stack.Pop();   // Downcast
Console.WriteLine (s);             // sausage

object is a reference type, by virtue of being a class. Despite this, value types, such as int, can also be cast to and from object. To make this possible, the CLR must perform some special work to bridge the underlying differences between value and reference types. This process is called boxing and unboxing.

Note

In the section Generics, we’ll describe how to improve our Stack class to better handle stacks with same-typed elements.

Boxing and Unboxing

Boxing is the act of casting a value-type instance to a reference-type instance. The reference type may be either the object class or an interface (see Interfaces). In this example, we box an int into an object:

int ...

Get C# 5.0 Pocket Reference now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.