Wednesday, November 02, 2005

CAST or AS

CAST or AS


If compiler knows the type of the object it is casting, it checks to see if it is a valid cast. If not, throws a compile time error.
If the compiler doesn't know the actual type of the object, it passes compilation.
Now the runtime checks if the object is of right type (the same type or a
derived type) or not.
If you use as operator, and the object is not of right type, then the reference is set to null.
If you use cast, and the object is not of right type, then the reference is not changed (i.e., NOT set to null)





















  DataTable o; ArrayList arr = new
ArrayList();

arr.Add(null);


object o = arr[0];


ArrayList arr = new
ArrayList();

arr.Add(new DataTable());


object o = arr[0];


MyType m = (MyType)o; Compiler: Throws an error [Cannot convert from DataTable to
MyType]
Compiler : GOOD

Run-time : GOOD


m is now set to null [Run time thinks that null can be converted to
MyType and so does the conversion and assigns the result of conversion
(null) to m]


Compiler : GOOD

Run-time : Throws an exception [Specified cast is not valid]


m still points to the object it was originally pointing to. [It is not
assigned null]


MyType m = o as MyType;

 


Compiler: Throws an error [Cannot convert from DataTable to
MyType via a built-in conversion]
Compiler : GOOD

Run-time : GOOD


m is now null [As o is not of the right type, the "as"
operator returns null which is assigned to m]


Compiler : GOOD

Run-time : GOOD


m is now null [As o is not of the right type, the "as"
operator returns null which is assigned to m]