The first type of cast is called an "explicit cast" and the second cast is actually a conversion using the as
operator, which is slightly different than a cast.
The explicit cast (type)objectInstance
will throw an InvalidCastException
if the object is not of the specified type.
// throws an exception if myObject is not of type MyTypeObject.
MyTypedObject mto = (MyTypedObject)myObject;
The as
operator will not throw an exception if the object is not of the specified type. It will simply return null
. If the object is of the specified type then the as
operator will return a reference to the converted type. The typical pattern for using the as
operator is:
// no exception thrown if myObject is not MyTypedObject
MyTypedObject mto = myObject as MyTypedObject;
if (mto != null)
{
// myObject was of type MyTypedObject, mto is a reference to the converted myObject
}
else
{
// myObject was of not type MyTypedObject, mto is null
}
Take a look at the following MSDN references for more details about explicit casting and type conversion: