Possible Duplicate:
Direct casting vs 'as' operator?
Where could this operator be useful? Instead of writing this:
Asset a = new Asset();
Stock s = a as Stock; // s is null; no exception thrown
if (s != null) Console.WriteLine (s.SharesOwned);
You’d better write something that throws. I saw tons of
(s != null)
in production code and it really becomes ugly. Exceptions are more descriptive and natural in that way. Even conceptually: how can you get no asset if it is not a stock? It should an exception if it is not a stock.
You often have the case where you don’t want an exception to be thrown because, well, the situation isn’t exceptional. You have a
frobobject which you know can be aFoo, but could also be aBar. So you want to perform some action only if it’s aFoo.You try to avoid these situations in designs, and use virtual methods instead. But sometimes there’s just no good way around that.
So rather than taking the roundabout way,
you do it directly:
If nothing else, this is at least more efficient since you only need to test for type equality once (inside the
ascast) instead of twice (in theisand in the cast).As a concrete example, this is very useful when you want to clear all the input boxes in a form. You could use the following code:
Using an exception here would make no sense.