473,397 Members | 2,099 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

Casting using "as" question

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

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

vs.

HttpWebRequest myReq = WebRequest.Create("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 1968
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**@discussions.microsoft.com> wrote in message
news:F6**********************************@microsof t.com...
What is the benefit of using "as" vs the other?

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

vs.

HttpWebRequest myReq = WebRequest.Create("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.Create("http://www.contoso.com/"); --This
will cause an exception of InvalidCastException if the system can cast the
web request as a httpwebrequest. But if we were to use "as"

vs.

HttpWebRequest myReq = WebRequest.Create("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**@discussions.microsoft.com> wrote in message
news:F6**********************************@microsof t.com... What is the benefit of using "as" vs the other?

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

vs.

HttpWebRequest myReq = WebRequest.Create("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.Create("http://www.contoso.com/");

vs.

HttpWebRequest myReq = WebRequest.Create("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.Create("http://www.contoso.com/");

vs.

HttpWebRequest myReq = WebRequest.Create("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
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...
1
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...
72
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...
1
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
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...
10
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,...
5
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...
6
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...
2
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... : ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...
0
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...
0
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,...

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.