The object Type

object (System.Object) is the ultimate base class for all types. Any type can be 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 LIFO——“Last in, First out.” 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 obj)
	    { data[position++] = obj; }

	  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");

	// Explicit cast is needed because we're downcasting:
	string s = (string) stack.Pop();

	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, and so be added to our stack. This feature of C# is called type unification:

	stack.Push (3);
	int three = (int) stack.Pop();

When you cast between a value type and object, the CLR must perform some special work to bridge the difference in semantics between value and reference types. This process is called boxing and unboxing.

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 (which we ...

Get C# 3.0 Pocket Reference, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.