Information Technology Reference
In-Depth Information
Yo u s h o u l d n e v e r w r i t e t h i s u g l y c o d e , b u t i t d o e s i l l u s t r a t e a c o m m o n
problem. Although you would never write this, you can use an object
parameter to a function that expects the proper conversions:
object o = Factory .GetObject();
DoStuffWithObject(o);
private static void DoStuffWithObject( object o)
{
try
{
MyType t;
t = ( MyType )o; // Fails. o is not MyType
// work with T, it's a MyType.
}
catch ( InvalidCastException )
{
// report the conversion failure.
}
}
Remember that user-defined conversion operators operate only on the
compile-time type of an object, not on the runtime type. It does not mat-
ter that a conversion between the runtime type of o and MyType exists.
The compiler just doesn't know or care. This statement has different
behavior, depending on the declared type of st:
t = ( MyType )st;
This next statement returns the same result, no matter what the declared
type of st is. So, you should prefer as to casts—it's more consistent. In fact,
if the types are not related by inheritance, but a user-defined conversion
operator exists, the following statement will generate a compiler error:
t = st as MyType ;
Now that you know to use as when possible, let's discuss when you can't
use it. The as operator does not work on value types. This statement won't
compile:
object o = Factory .GetValue();
int i = o as int ; // Does not compile.
Search WWH ::




Custom Search