Live data from Hacker News

The as Operator

gimmecsharp.blogspot.com

1–3 of 3 posts

Re: The as Operator

#2
Hmm. The article says that the as operator is the same as casting, which is not correct. Casting will result in an exception if coercion fails, where as 'as' will return a null reference.

Which makes the code example

   (foo as Bar).Method();
dangerous without a guard.

Edit: punctuated for clarity.

Re: The as Operator

#3
post #2

Hmm. The article says that the as operator is the same as casting, which is not correct. Casting will result in an exception if coercion fails, where as 'as' will return a null reference. Which makes the code example (foo as Bar).Method(); dangerous without a guard. Edit: punctuated for clarity.

You can always use the null coalescing operator.

(foo as Bar ?? new Bar()).Method();