codymanix said:
No, "as" is not faster than a cast.
Um, yes it is (on .NET 1.1, at least). Not by very much, but it is.
See
http://groups.google.com/groups?selm=MPG.1acca34b9f6b3a7d98a485%
40msnews.microsoft.com&rnum=4
(aka
http://tinyurl.com/2o44v) for evidence of this.
But if you are querying the type and then determine wheather to cast or not
is a difference:
if (a is MyClass)
{
b = (MyClass)a;
}
Because the system has to determine the type twice here.
Yes - that's *really* slow. That doesn't mean that a cast itself is as
quick as using "as", however.
But if you do b = a as MyClass or b = (MyClass)a there should be no
difference in speed.
Except there is, demonstrably. What makes you think there shouldn't be?
The problem is the the nullreferenceexception can occur very late in the
program or maybe never.
That's true, if *and only if* you don't then immediately dereference
the result.
The program does not behave as it should and you don't know why. It is very
diffycult to tell where in the program the error has its origin then.
But when you use a cast instead you know immediately when there is someting
wrong.
Sure. Using as and then immediately dereferencing the value lets you
know *almost* as immediately, and pretty much just as usefully though.
In some cases, it gives you more readable code - and in those cases, I
would have no problem with using "as".
The meaning of a cast is "I know that it is that type and if not an error
immediately reports that there is someting wrong".
The meaning of as is "Maybe it is the type I assume, I will immediately test
if for null to determine if it really was the type I assumed".
No, the meaning of "as" is (from the C# specification):
<quote>
The as operator is used to explicitly convert a value to a given
reference type using a reference conversion or a boxing conversion.
Unlike a cast expression, the as operator never throws an exception.
Instead, if the indicated conversion is not possible, the resulting
value is null.
</quote>
As I said, a common *use* of that is to then immediately test for
nullity, but it's by no means required.