C # is a strong data type language. Good programming practice means that when you can avoid coercion from one data type to another, we should try our best to avoid it. At some point, however, runtime type detection is unavoidable. In C #, most of the time you want to use the System.Object type for the arguments that invoke the function, because Framwork has defined the prototype of the function for us. You are likely to try to convert those types down into other types of interfaces or classes. You have two choices: use the as operator, or, using the old C style, cast. (Either way, you must also protect the variable: You can try to convert using is, but then convert or cast with AS.)
At any time, the correct choice is to use the as operator for type conversions. Because it is more secure than blind coercion and more efficient at runtime. When converting with the AS and is operators, not all user-defined types can be completed. They are only successful when the Run-time type matches the target type. They will never construct a new object to satisfy the (transformation) requirements.
Look at an example. You write a code that converts an object instance of any type to an instance of a MyType type. That's how you write code:
object o = Factory.GetObject( );
// Version one:
MyType t = o as MyType;
if ( t != null )
{
// work with t, it's a MyType.
} else
{
// report the failure.
}
Or you write this:
object o = Factory.GetObject( );
// Version two:
try {
MyType t;
t = ( MyType ) o;
if ( t != null )
{
// work with T, it's a MyType.
} else
{
// Report a null reference failure.
}
} catch
{
// report the conversion failure.
}