I know the function of this keyword, but I would like to know how it works on a lower level.
Which one is faster? And do they always yield the same result? If they do, why are there two different ways?
// Is there an overhead? An internal try catch?
Class123 obj = someobject as Class123;
if (Class123 != null)
{
//OK
}
or
Class123 obj = null;
if (someobject is Class123)
{
obj = (Class123)someobject;
}
There’s no internal try-catch happening when using the
askeyword. The functionality is built in to the compiler/CLR, as far as I know, so the type check is implicit and automated.Simple rule:
Use a direct cast when you always expect the object to have a known type (and thus receive a helpful error if it is by chance of the wrong type). Use the
askeyword when the object is always of a known type.The reason for the existance of the
askeyword is purely for the convenience of the programmer (although you are correct in suggesting that a try-catch would be slower). You could implement it yourself manually as such, as you point out:This highlights the fact that the ‘as’ keyword is primarily there for the purpose of conciseness.
Now, the performance difference between the two is likely to be negligible. The
askeyword is probably marginally slower because of the type check, but this is unlikely to affect code in the vast majority of situations. As oft said, premature optimisation is never a wise thing to be doing. Benchmark if you really wish, but I would advise just to use whichever method is more convenient/appropiate for your situation, and not worry about performance at all (or later if you absolutely must).