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.Diagnostics;
public class Test
{
static void Main(string[] args)
{
object o = "hello";
int iterations = int.Parse(args[0]);
int total = 0;
Stopwatch sw = Stopwatch.StartNew();
for (int i=0; i < iterations; i++)
{
total += Cast(o).Length;
}
sw.Stop();
Console.WriteLine(total);
Console.WriteLine(sw.ElapsedMilliseconds);
}
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
NullReferenceException instead of an InvalidCastException 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