Since standard casting is common, and its use is known well
to most developers, I will only be demonstrating how to use the as operator
effectively.
In the simplest case, we are converting an object to a type
which is a reference type. After performing the conversion we need to make sure
that it worked. We check for the null value, and as long as it is not null, we
work with our new variable.
Listing 4: Checking For Null after Conversion
MyType converted = myObj as MyType;
if (converted != null)
{
// work with the object here
// we know the conversion worked.
}
In the above example, MyType is a reference type. By now you
have probably noticed that I have been mentioning reference types for this
example. If you read my article explaining the difference between value and reference types in C#,
then you already know that only value types can be null. I also mentioned the
importance of Nullable value types, which brings me to my next example of using
this. If you want to use the "as" operator to convert to a value
type, you will need to actually use a Nullable version of the value type.
As a simple example I will convert a double object to an
integer using the technique I have described here.
Listing 5: Conversion Using Value Type Objects
object myObj = 0.0;
int? converted = myObj as int?;
if (converted != null)
{
// work with the object here
// we know the conversion worked.
}
Conversion used to Check Type
You pretty much never ever want to do this. It is a bad
practice I have seen used before, and I have seen people suggest it in forums.
It is quite crazy. What am I talking about here? I have seen code where people
wrapped a try-catch block around standard casting, and the developer was merely
doing this to check the type of the object.
I have also seen people use the "as" operator to
check to see if the object is of the destination type. Well, there is an
operator specifically for this. The operator is called "is" and is
used to determine if one expression is of a certain type. Keep in mind that to
use either "is" or "as" the type you are checking must be a
reference type.