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

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


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-25 2:48:33 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search