The Object Type

System.Object is the base class for all types. Any type can be upcast to object. Object is a reference type, however you can cast between value type and object with the process of boxing and unboxing.

Boxing and Unboxing

Boxing

Converting value-type instance to a reference-type instance (object class or interface). Copies the value-type instance into the new object.

Unboxing

Requires an explicit cast. Throws InvalidCastException if the stated value type doesn’t match the actual type. Copies the contents of the object into a value-type instance.

int x = 9;
object obj = x;           // Box the int
int y = (int)obj;         // Unbox the int

//InvalidCastException
object obj = 9;
long x = (int) obj;

Static and Runtime Type Checking

Static checking

Checking during compile time, it is to verify the correctness of program without running it.

Runtime Checking

Checked by the CLR during runtime such as when you apply the unboxing.

int i = 3;
object boxed = i;
i = 5;
Console.WriteLine (boxed);    // 3

The GetType Method and typeof Operator

System.Type object represent all types in C#. It can be checked using GetType method or typeof operator. It has properties such as name, assembly, base type, etc.

GetType Method is evaluated during runtime whereas typeof Operator statically compiled.

static void Main()
{
	Point p = new Point();
	Console.WriteLine (p.GetType().Name);             // Point
	Console.WriteLine (typeof (Point).Name);          // Point
	Console.WriteLine (p.GetType() == typeof(Point)); // True
	Console.WriteLine (p.X.GetType().Name);           // Int32
	Console.WriteLine (p.Y.GetType().FullName);       // System.Int32
}

public class Point { public int X, Y; }

The ToString Method

ToString() methods returns the default text representation of a type instance, however you can override the ToString() method on custom types.

static void Main()
{
	int x = 1;
	string s = x.ToString();     // s is "1"
	
	Panda p = new Panda { Name = "Petey" };
	Console.WriteLine (p.ToString()); 		// Petey
}

// You can override the ToString method on custom types:

public class Panda
{
	public string Name;
	public override string ToString() { return Name; }
}

Leave a Reply

Your email address will not be published. Required fields are marked *