Possible Duplicate:
Casting vs using the ‘as’ keyword in the CLR
I know there are a lot of questions about casts but I don’t know the specific names of these two casts so I’m not sure where to look. What are the differences between the two casts below?
TreeNode treeNode = (TreeNode)sender; // first cast
TreeNode treeNode = (sender as TreeNode); //second cast
The first type of cast is called an “explicit cast” and the second cast is actually a conversion using the
asoperator, which is slightly different than a cast.The explicit cast
(type)objectInstancewill throw anInvalidCastExceptionif the object is not of the specified type.The
asoperator will not throw an exception if the object is not of the specified type. It will simply returnnull. If the object is of the specified type then theasoperator will return a reference to the converted type. The typical pattern for using theasoperator is:Take a look at the following MSDN references for more details about explicit casting and type conversion: