AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1811&pId=-1
Standard Type Casting and "as" Operator Conversions
page
by Brendan Enrick
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 29578/ 95

Introduction

C# has two primary ways of changing the types of objects from one type to another. There is the standard casting performed by naming the type to cast to before the expression to cast from inside of a set of parentheses. The other way is to use the as operator.

Listing 1: Basic Type Casting

object myIntObj = 1;
int myInt = (int)myIntObj;

Listing 2: Basic Use of the "as" Operator

object myStringObj = "Brendan Enrick";
string myString = myStringObj as string;

I am sure pretty everyone has seen both of these, but something more important than just knowing about them is knowing what they do and when to use each one. The goal of this article is to explain when each should be used and why.

Understanding the Basics

Simple type casting is pretty well understood. You change the type of an object at runtime from one type to another. The common scenario is to convert from a less specific to a more specific type. For example, we might be converting from an object to an integer. If our current instance of type object is not really an integer or anything that can safely cast to an integer we will throw an exception. This can be a good or a bad outcome for our program. It is good that the program does not continue executing with incorrect data, but the program either crashed or handled the exception.

The as operator obviously also changes the type of an object, but it does so in a different way. When the as operator receives an object which is not of the destination type, it instead returns the null value. Yes, this means that object you are casting to must be nullable, which means it must be a reference type.

Note: If you are trying to use the "as" operator on a value type object you will need to use a nullable value type. Read the following references for more info on these.

Information on Value Types and Reference Types

Information on null and Nullable Value Types

When to Use Each Form of Conversion

In my experience, I have found it to be a good idea to use the casting operator when it should be unlikely for the casting to fail. This way if there is a problem we definitely know about the error and handle the situation. When deciding whether to catch or check for exceptions, it is important to consider the likelihood of the error occurring. If the error is likely, check for it, and if the error is a problem and not just bad user input or something similar, handle it by catching the thrown exception.

Since the "as" operator is able to handle things safely, it should generally be used when you will not be certain if the value of the object to be converted will cast correctly. Since we are saying in this case it is not irregular for the object to be an invalid type, it is much better for the software to handle the problem safely by using "as," which ensures the correct type without using exception handling.

According to Microsoft's documentation, using the "as" operator is equivalent to using the following code, except that the "expression" defined in the snippet is only evaluated once.

Listing 3: "as" Operator Equivalent Code

expression is type ? (type)expression : (type)null

The "expression" there could be any expression we were using to cast as a different type, so for the simplicity of the previous explanation it is the original object we are casting to the new type. The following is an example situation. Keep in mind that we do not have a performance decrease here for evaluating the expression twice, because the "as" operator will only evaluate it one time.

Using the "as" Operator

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.

Conclusion

Working with conversion of types in C# is not all that complicated. We have looked at standard casting as well as using the "as" operator to convert between types. Keep in mind the importance of reference types with the "as" operator, and try to only use it when there is a high likelihood that the conversion will not work or if the failure to convert is not an error. If the situation is unlikely to occur, then you should cast the object and handle the exception. This way you make sure that you are actually taking care of the error if it occurs.

Read more from this author on his blog.



©Copyright 1998-2014 ASPAlliance.com  |  Page Processed at 10/25/2014 7:31:51 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search