Standard Type Casting and "as" Operator Conversions
page 1 of 5
Published: 09 Feb 2009
Converting objects from one type to another is a common practice in software development. When dealing with this, it is important to understand the difference between standard casting and using the "as" operator to convert. In this article, Brendan explains this difference and when to use each type of conversion. His code snippets demonstrate the information he is explaining in the article.
by Brendan Enrick
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 26616/ 63


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.

View Entire Article

User Comments

Title: hjk   
Name: hgjk
Date: 2012-06-14 2:05:34 AM
Title: Thank you for your help.   
Name: Jose Amayo
Date: 2009-10-30 12:16:52 PM
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  |  Page Processed at 2024-05-20 4:26:17 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search