473,718 Members | 1,977 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Casting using "as" question

What is the benefit of using "as" vs the other?

HttpWebRequest myReq
= (HttpWebRequest )WebRequest.Cre ate("http://www.contoso.com/");

vs.

HttpWebRequest myReq = WebRequest.Crea te("http://www.contoso.com/") as
HttpWebRequest;

Based on the MS documenation "The as operator is like a cast except that it
yields null on conversion failure instead of raising an exception. "

I've read some internal coding standards that state "Use the as operator to
defensively cast to a type", but I don't quite get the benefit of this and
want an outside opinion.

Thanks.

Jan 20 '06 #1
5 2010
It returns an object of the resulting cast (if successful) or null. So you
can use the object afterwards and it doesn't raise an exception (just like
the MS documentation states).

Best regards,
--
Angel J. Hernández M.
MCP - MCAD - MCSD - MCDBA
Microsoft MVP ASP/ASP.NET
http://groups.msn.com/desarrolladoresmiranda
http://www.consein.com

"Dave" <Da**@discussio ns.microsoft.co m> wrote in message
news:F6******** *************** ***********@mic rosoft.com...
What is the benefit of using "as" vs the other?

HttpWebRequest myReq
= (HttpWebRequest )WebRequest.Cre ate("http://www.contoso.com/");

vs.

HttpWebRequest myReq = WebRequest.Crea te("http://www.contoso.com/") as
HttpWebRequest;

Based on the MS documenation "The as operator is like a cast except that
it
yields null on conversion failure instead of raising an exception. "

I've read some internal coding standards that state "Use the as operator
to
defensively cast to a type", but I don't quite get the benefit of this and
want an outside opinion.

Thanks.

Jan 20 '06 #2
Using "as" allows for the "graceful" failure of casting one object to
another.
As per your examples:
HttpWebRequest myReq
= (HttpWebRequest )WebRequest.Cre ate("http://www.contoso.com/"); --This
will cause an exception of InvalidCastExce ption if the system can cast the
web request as a httpwebrequest. But if we were to use "as"

vs.

HttpWebRequest myReq = WebRequest.Crea te("http://www.contoso.com/") as
HttpWebRequest; -- this will capture the possible exception and return a
null allowing for your code to be execute as normal.
Think of "as" as being
public static void as(ref object a, object b, Type someType){
try{
a = (someType)b;
}catch{ a = null;}
}
}
In some cases using "as" is much safer than attempting to forceably cast one
type to another type.

Thaddaeus

"Dave" <Da**@discussio ns.microsoft.co m> wrote in message
news:F6******** *************** ***********@mic rosoft.com... What is the benefit of using "as" vs the other?

HttpWebRequest myReq
= (HttpWebRequest )WebRequest.Cre ate("http://www.contoso.com/");

vs.

HttpWebRequest myReq = WebRequest.Crea te("http://www.contoso.com/") as
HttpWebRequest;

Based on the MS documenation "The as operator is like a cast except that
it
yields null on conversion failure instead of raising an exception. "

I've read some internal coding standards that state "Use the as operator
to
defensively cast to a type", but I don't quite get the benefit of this and
want an outside opinion.

Thanks.

Jan 20 '06 #3
> What is the benefit of using "as" vs the other?

HttpWebRequest myReq
= (HttpWebRequest )WebRequest.Cre ate("http://www.contoso.com/");

vs.

HttpWebRequest myReq = WebRequest.Crea te("http://www.contoso.com/") as
HttpWebRequest;

Based on the MS documenation "The as operator is like a cast except that it
yields null on conversion failure instead of raising an exception. "

I've read some internal coding standards that state "Use the as operator to
defensively cast to a type", but I don't quite get the benefit of this and
want an outside opinion.

Thanks.


And an extra remark:

unlike a direct cast, you can't use "as" on value types
("theobj as int"), because it can return null, which value-types can't
handle.

Hans Kesting
Jan 20 '06 #4
Hans Kesting wrote:
And an extra remark:

unlike a direct cast, you can't use "as" on value types
("theobj as int"), because it can return null, which value-types can't
handle.


That's not strictly true under .NET 2.0. Nullable<T> types are still
value types, but can be used with "as":

using System;

class Test
{
static void Main()
{
object o = 5;
int? x = o as int?;
}
}

(Note that if you remove the last ? in the program, you'll get a
compiler error CS0077 which has an inaccurate description - I've
reported it to MS).

Jon

Jan 20 '06 #5
Internally, they are two different CIL instructions -- castclass
(straight cast) and isinst (as.) The primary difference, as noted
already is that the castclass instruction generates an exception when no
cast exists while the isinst just places a null value on the evaluation
stack.

The implication is that if you know -- or expect your type to always be
castable then the castclass instruction provides some runtime safety in
case an unexpected value comes through -- and you dont suffer the
penalty of spinning up an exception. If, on the other hand, you are not
sure what the type will be, and you want to handle it gracefully, then
isinst allows you to avoid the performance penalties of an exception if
the class cannot be cast.

Dave wrote:
What is the benefit of using "as" vs the other?

HttpWebRequest myReq
= (HttpWebRequest )WebRequest.Cre ate("http://www.contoso.com/");

vs.

HttpWebRequest myReq = WebRequest.Crea te("http://www.contoso.com/") as
HttpWebRequest;

Based on the MS documenation "The as operator is like a cast except that it
yields null on conversion failure instead of raising an exception. "

I've read some internal coding standards that state "Use the as operator to
defensively cast to a type", but I don't quite get the benefit of this and
want an outside opinion.

Thanks.

Jan 20 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

49
2854
by: Ville Vainio | last post by:
I don't know if you have seen this before, but here goes: http://text.userlinux.com/white_paper.html There is a jab at Python, though, mentioning that Ruby is more "refined". -- Ville Vainio http://www.students.tut.fi/~vainio24
1
2046
by: Walt | last post by:
We are using ASP.net to develop a new website. The old website uses legacy ASP connecting to an Oracle database (9.2, W2k3, charecter set WE8ISO8859P1). The new site connects to the same database but using ASP.NET. Our problem is that extended characters are printing out as question marks. In particular, the "smart quote" characters that MS Word likes to use are showing up as question marks. We ran into a similar problem with the...
72
4204
by: Paminu | last post by:
In math this expression: (a < b) && (b < c) would be described as: a < b < c But why is it that in C these two expressions evaluate to something different for the same values of a, b and c?
1
3631
by: Alex | last post by:
Is that "as" returns null if failed to cast, doesn't throw an exception, so you can check the reference for null afterwards. straight casting will throw an InvalidCastException exception.
15
2552
by: Bobby C. Jones | last post by:
Is there an advantage to either of these methods, or is it simply a matter of style? I used to use the "as" method, but later gave it up for the "is" method as the intent of the code seems a little clearer to me. I now have some projects coming up where the baseTypeCollection will contain 5k to 10k objects that will have to be searched for various sub types of which I only expect to find ~50 to ~100 matches. Thanks! foreach (baseType...
10
1343
by: Max André Bündchen | last post by:
Hi, I must design a method that receive a Control object and return a single value if it is a TextBox object, another value if it is a ComboBox object and so on. If I try a "if-else-if" loop, this will be very unhappy! Can I use a foreach to make that? How declare and create the array for use in the operator "is" (for test a Control, like "cont is TextBox")?
5
9664
by: Hayato Iriumi | last post by:
When converting a type to another using CType and if the type conversion fails, it throw an exception. However, in C#, there is a keyword "as" which only makes the variable Nothing (null) without throwing an exception. Is there a plan at Microsoft VB .NET team to include a keyword equivalent to "as"?
6
1354
by: Jake Barnes | last post by:
This function has always worked for me just fine: function nl2br_js(myString){ // 02-18-06 - this function imitates the PHP command nl2br, which finds newlines in a string // and replaces them with newlines plus HTML BR tags. Is the easiest way to create the // appearance of paragraphs when people are creating web pages by typing text into a form. var regXString = "\\n"
2
2891
by: sherifffruitfly | last post by:
Hi, I'm using an adaptation of excel-reading code that's all over the internet - I don't much like or understand it, but it has worked for me in the past.... beggars can't be choosers... : Excel.Application excelObj = new Excel.Application(); Excel.Workbook theWorkbook = excelObj.Workbooks.Open(path+filename, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false,
0
9207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9120
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9053
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7987
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6652
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5971
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4741
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3182
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2553
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.