Standard Type Casting and "as" Operator Conversions
page 3 of 5
by Brendan Enrick
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 26731/ 27

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.


View Entire Article

User Comments

Title: hjk   
Name: hgjk
Date: 2012-06-14 2:05:34 AM
Comment:
hhjkghjkjhk
Title: Thank you for your help.   
Name: Jose Amayo
Date: 2009-10-30 12:16:52 PM
Comment:
Hello Brendan,
Thank you very much for taking the time to write this article and the one explaining the difference between value and reference types. They were invaluable in helping me tweak an ASP.NET project I am working on.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-17 11:32:08 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search