Information Technology Reference
In-Depth Information
// Version two:
try
{
MyType t1;
t1 = ( MyType )o; // Fails. o is not MyType
// work with t1, it's a MyType.
}
catch ( InvalidCastException )
{
// report the conversion failure.
}
Both versions fail. But I told you that casts will perform user-defined con-
versions. You'd think the cast would succeed. You're right—it should suc-
ceed if you think that way. But it fails because your compiler is generating
code based on the compile-time type of the object, o. The compiler knows
nothing about the runtime type of o; it views o as an instance of object .
The compiler sees that there is no user-defined conversion from object to
MyType. It checks the definitions of object and MyType. Lacking any
user-defined conversion, the compiler generates the code to examine the
runtime type of o and checks whether that type is a MyType. Because o is
a SecondType object, that fails. The compiler does not check to see whether
the actual runtime type of o can be converted to a MyType object.
Yo u c o u l d m a k e t h e c o n v e r s i o n f r o m S e c o n d Ty p e t o M y Ty p e s u c c e e d i f
you wrote the code snippet like this:
object o = Factory .GetObject();
// Version three:
SecondType st = o as SecondType ;
try
{
MyType t;
t = ( MyType )st;
// work with T, it's a MyType.
}
catch ( InvalidCastException )
{
// report the failure.
}
 
Search WWH ::




Custom Search