473,706 Members | 2,324 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

about casting

Hello!

Here I have two different way to use casting.
Is any of these any better then the other?
Or is it just a question of taste.

newCards.Add((C ard)sourceCard. Clone());
newCards.Add(so urceCard.Clone( ) as Card);

//Tony
Jun 27 '08 #1
29 1853
Tony Johansson <jo************ *****@telia.com wrote:
Here I have two different way to use casting.
Is any of these any better then the other?
Or is it just a question of taste.

newCards.Add((C ard)sourceCard. Clone());
newCards.Add(so urceCard.Clone( ) as Card);
Using "as" doesn't throw an exception if the cast fails - it just
returns null instead.

Using a direct cast also allows for user-defined conversions etc.

I tend to use "as" for values I'm in doubt about - when I'm about to
test the result:

Object unknown = GetMeSomeData() ;
string text = unknown as string;
if (text != null)
{
...
}
I use direct casting when I really, really expect it to succeed - i.e.
when a failure indicates a problem which should be reported as an
exception:

Object shouldBeString = GetMeSomeText() ;
string text = (string) shouldBeString;

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #2
One other note; "as" can only be used with reference types and
Nullable<T>, as it can't return null for a regular struct. You'd need
to use "is" and cast to achieve the same.

Marc
Jun 27 '08 #3
Tony,

I use "as" because it is much faster than the "(Card)" variety of casting.
Also, I think "(vehicle as Car).Color" looks a lot cleaner than "((Car)
vehicle).Color" . That's my preference though - others might think "(Car)"
looks better. Let me preempt my fellow NGers by saying that you should only
optimize yada yada yada. I say, ya know what, I'm developing on mobile
devices running a 200MHz, I'm gonna use every little speed enhancement I can
get especially when it is for free.

Very important to note is that they are different as Jon pointed out, so
sometimes it makes sense to use one instead of the other.

Anyway, there you go.

Hilton

"Tony Johansson" <jo************ *****@telia.com wrote in message
news:pk******** *****@newsb.tel ia.net...
Hello!

Here I have two different way to use casting.
Is any of these any better then the other?
Or is it just a question of taste.

newCards.Add((C ard)sourceCard. Clone());
newCards.Add(so urceCard.Clone( ) as Card);

//Tony

Jun 27 '08 #4
Hilton,
Why is 'as' much faster that (Card), except in cases where (Card) might
throw an exception?
Otherwise, I think in both cases the CLR needs to walk the same level of
object type structures and so should be have the same running time.

Sujeet

"Hilton" wrote:
Tony,

I use "as" because it is much faster than the "(Card)" variety of casting.
Also, I think "(vehicle as Car).Color" looks a lot cleaner than "((Car)
vehicle).Color" . That's my preference though - others might think "(Car)"
looks better. Let me preempt my fellow NGers by saying that you should only
optimize yada yada yada. I say, ya know what, I'm developing on mobile
devices running a 200MHz, I'm gonna use every little speed enhancement I can
get especially when it is for free.

Very important to note is that they are different as Jon pointed out, so
sometimes it makes sense to use one instead of the other.

Anyway, there you go.

Hilton

"Tony Johansson" <jo************ *****@telia.com wrote in message
news:pk******** *****@newsb.tel ia.net...
Hello!

Here I have two different way to use casting.
Is any of these any better then the other?
Or is it just a question of taste.

newCards.Add((C ard)sourceCard. Clone());
newCards.Add(so urceCard.Clone( ) as Card);

//Tony


Jun 27 '08 #5
Actually, I think the DirectCast version: (string) x is faster (by design)
as long as you don't get an exception because that version is meant to do
the cast without checking to see if the cast is doable first.

-Scott
"Sujeet" <Su****@discuss ions.microsoft. comwrote in message
news:63******** *************** ***********@mic rosoft.com...
Hilton,
Why is 'as' much faster that (Card), except in cases where (Card) might
throw an exception?
Otherwise, I think in both cases the CLR needs to walk the same level of
object type structures and so should be have the same running time.

Sujeet

"Hilton" wrote:
>Tony,

I use "as" because it is much faster than the "(Card)" variety of
casting.
Also, I think "(vehicle as Car).Color" looks a lot cleaner than "((Car)
vehicle).Color ". That's my preference though - others might think
"(Car)"
looks better. Let me preempt my fellow NGers by saying that you should
only
optimize yada yada yada. I say, ya know what, I'm developing on mobile
devices running a 200MHz, I'm gonna use every little speed enhancement I
can
get especially when it is for free.

Very important to note is that they are different as Jon pointed out, so
sometimes it makes sense to use one instead of the other.

Anyway, there you go.

Hilton

"Tony Johansson" <jo************ *****@telia.com wrote in message
news:pk******* ******@newsb.te lia.net...
Hello!

Here I have two different way to use casting.
Is any of these any better then the other?
Or is it just a question of taste.

newCards.Add((C ard)sourceCard. Clone());
newCards.Add(so urceCard.Clone( ) as Card);

//Tony



Jun 27 '08 #6
On Jun 12, 2:44 am, "Hilton" <nos...@nospam. comwrote:
I use "as" because it is much faster than the "(Card)" variety of casting.
No it's not. At least, it's not on the desktop CLR.

It's faster to use "as" and then a comparison with null than it is to
use "is" and then a direct cast, but if you're just casting then
they're about the same - with casting coming out slightly on top in
one microbenchmark I've just run:

using System;
using System.Diagnost ics;

public class Test
{
static void Main(string[] args)
{
object o = "hello";
int iterations = int.Parse(args[0]);
int total = 0;
Stopwatch sw = Stopwatch.Start New();
for (int i=0; i < iterations; i++)
{
total += Cast(o).Length;
}
sw.Stop();
Console.WriteLi ne(total);
Console.WriteLi ne(sw.ElapsedMi lliseconds);
}

static string Cast(object o)
{
return (string)o;
}

static string As(object o)
{
return o as string;
}
}

Change the call appropriately to test the different methods, and then
change the calling code to have the cast/as directly in the loop:

Running with 2,000,000,000 iterations, 3 runs each
As: 9595, 9567m 9565
Cast: 7180, 7199, 7216
As inline: 6355, 6393, 6595
Cast inline: 4777, 4807, 4812

Normal caveats about microbenchmarks apply, but I'd be interested to
see the results of you running the above tests on the CF. It certainly
looks to me like "as" is marginally slower, and certainly far from
"much faster".
Also, I think "(vehicle as Car).Color" looks a lot cleaner than "((Car)
vehicle).Color" . That's my preference though - others might think "(Car)"
looks better. Let me preempt my fellow NGers by saying that you should only
optimize yada yada yada. I say, ya know what, I'm developing on mobile
devices running a 200MHz, I'm gonna use every little speed enhancement I can
get especially when it is for free.
Except it's not for free anyway - it means you get a
NullReferenceEx ception instead of an InvalidCastExce ption if
anything's wrong, and that's if you're lucky and use the referece
immediately. Using "as" when you really expect a cast to work can
obscure the origin of a bug.
Very important to note is that they are different as Jon pointed out, so
sometimes it makes sense to use one instead of the other.
One thing I didn't mention about the difference between the two is
nulls. If you cast and end up with null, you know that the source was
null. If you use "as" and end up with null, it's either because the
original reference was null *or* because it referred to an object of
the wrong type.

Jon
Jun 27 '08 #7
On Jun 12, 4:19 am, "Scott M." <s...@nospam.no spamwrote:
Actually, I think the DirectCast version: (string) x is faster (by design)
as long as you don't get an exception because that version is meant to do
the cast without checking to see if the cast is doable first.
No, it's still got to do the cast to see whether or not you *do* get
an exception. As it happens it seems like it's marginally faster on
the current desktop CLR - I think it may have been the other way round
at some point. The important part is that both of them actually need
to do the same expensive bit of work: check whether a cast is valid.
What happens after that is relatively cheap (in the success case).

Jon
Jun 27 '08 #8
Jon Skeet wrote:
Normal caveats about microbenchmarks apply, but I'd be interested to
see the results of you running the above tests on the CF. It certainly
looks to me like "as" is marginally slower, and certainly far from
"much faster".
I remember doing this test after seeing an article in CodeProject and my
results definitely showed that "as" was much faster - see the CodeProject
article: http://69.10.233.10/KB/cs/csharpcasts.aspx

To verify before I posted my earlier post today, I ran some code on my
desktop. The two inner loops looked like:

{
Blob b = (Blob) o;
}

and

{
Blob b = o as Blob;
}

....and the second version was indeed *much* faster than the first, so I was
confident posting that it was much faster. Only when I went back and
thought about it, I realized that the compiler could safely remove "o as
Blob", but *not* "(Blob) o" - right? So, I was, in effect, testing compiler
optimization which I am glad to say is alive and well. OK, perhaps I had
originally tested in on CF 1. So I wrote a quick app, ran it on my X51 and
the two versions ran in exactly the same time (give or take). The
CodeProject guy never posted any code, perhaps he made the same "compiler
optimization" error as I did.

Interestingly though, the two are very different beasts, used in different
circumstances, and definitely help to self-document if used correctly. The
cool thing though is that C# has both of these tools.

OK, I was wrong - sorry about that and thanks to Jon for correcting me.

Hilton
Jun 27 '08 #9
On Jun 12, 8:26 am, "Hilton" <nos...@nospam. comwrote:
Jon Skeet wrote:
Normal caveats about microbenchmarks apply, but I'd be interested to
see the results of you running the above tests on the CF. It certainly
looks to me like "as" is marginally slower, and certainly far from
"much faster".

I remember doing this test after seeing an article in CodeProject and my
results definitely showed that "as" was much faster - see the CodeProject
article:http://69.10.233.10/KB/cs/csharpcasts.aspx
<snip>

Interestingly, there's a post there saying that the performance of
direct casting was significantly improved for .NET 2.0 - so that's
probably where the confusion comes from.

Now, for your particular case it's worth investigating whether that's
also true on the CF - or rather, for the particular version of the CF
you're using. I wouldn't be surprised if the performance
characteristics were quite different there.

<snip>
Interestingly though, the two are very different beasts, used in different
circumstances, and definitely help to self-document if used correctly. The
cool thing though is that C# has both of these tools.
Yes, it's definitely nice to have both. I do wonder whether "as" might
not be better as a slightly different language construct though -
something to do:

Foo x = y as Foo;
if (x != null)
{
...
}

in one block, e.g.:

when (Foo x = y)
{
...
}

I'm not sure though. (And I certainly wouldn't want to introduce it
now - just an idea of what might have been nice at 1.0.)

Jon
Jun 27 '08 #10

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

Similar topics

4
2509
by: drowned | last post by:
I'm having a problem understanding why the code in this little program I've got is behaving the way it does... if anyone can explain it, I'd be grateful: #include <iostream> using namespace std; //This function takes an unsigned char (one byte on my machine) //and prints it in binary notation
4
384
by: David Vestal | last post by:
I'm reading a 24-bit address from a char* named i_msg, and I expected these two snippets to be equivalent. They aren't; the first doesn't work. What gives? SNIPPET 1: unsigned long address; address = ((unsigned long) i_msg) << 16 + ((unsigned short) i_msg) << 8 + i_msg;
3
1528
by: Alfonso Morra | last post by:
Hi, I have two func ptr prototypes declared as : typedef void (*VFP)(void) ; typedef int(MyCallback*)(enum_1, enum2, int, void*) ; I hav a struct as ff: typedef struct {
3
1563
by: Barry Mossman | last post by:
Hi, I get the feeling that I am missing something with regards to casting. The CopyTo method allows me to copy the contents of a collection into an array. My collection is a MatchCollection produced by Regex. The Collection's entries are all valid strings. If I CopyTo to a string array it compiles ok, but fails at run time with an InvalidCastException. It works if I CopyTo an object array. ... does this mean that the MatchCollection's...
6
19204
by: Jim Bancroft | last post by:
Hi everyone, I'm having some trouble with the code below. I receive a compile-time error on the second line saying "; expected": private static void myTestFunction(long myLong) { System.Data.SqlTypes.SqlInt32 myTestInt;
3
2794
by: Dariusz Tomon | last post by:
Hi I'm trying to retrieve data from database (MS Sql serv) from field of BIT type. I'm trying like this: while (myReader.Read()) { Int16 cos = (Int16)myReader.GetSqlInt16(1);
3
1228
by: Andy Chen | last post by:
Hi, I have a Hashtable, key is string and value is ArrayList. The problem is I cannot cast the value from object to ArrayList. like this: Hashtable ht = new Hashtable(); ArrayList al = new ArrayList(); al.Add("test"); ht.Add("key1", al);
0
8781
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8993
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
7906
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...
0
5938
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
4448
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4709
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3147
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
2500
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2094
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.