Simple type casting is pretty well understood. You change
the type of an object at runtime from one type to another. The common scenario
is to convert from a less specific to a more specific type. For example, we
might be converting from an object to an integer. If our current instance of
type object is not really an integer or anything that can safely cast to an
integer we will throw an exception. This can be a good or a bad outcome for our
program. It is good that the program does not continue executing with incorrect
data, but the program either crashed or handled the exception.
The as operator obviously also changes the type of an
object, but it does so in a different way. When the as operator receives an
object which is not of the destination type, it instead returns the null value.
Yes, this means that object you are casting to must be nullable, which means it
must be a reference type.
Note: If you are trying to use the
"as" operator on a value type object you will need to use a nullable
value type. Read the following references for more info on these.
Information on Value Types and Reference Types
Information on null and Nullable Value Types