Posted on Saturday, October 20, 2007 at 2:32 PM
A little while back I answered a post on the PH forums about why you might need to use casts, and particularly why you might need to upcast. This article is a tidied up and extended version of my answer.
Variable vs. value types
Suppose we write a class B that inherits from class A. We can then say that B is a subclass of A. That means that you can use an object of type B anywhere that you can use an object of type A.
To understand upcasting and downcasting better, we need to introduce the idea of container or variable types and contrast them to value types. A variable may contain a value. For reference types, the variable has a type that states what type of value it can contain. However, the type of the value may be different; namely, it may be a subtype of the variable type. Let's clarify this with some examples.
A foo = new A(); // Variable type A, value type A
B bar = new B(); // Variable type B, value type B
A baz = new B(); // Variable type A, value type B...