Internally, they are two different CIL instructions -- castclass
(straight cast) and isinst (as.) The primary difference, as noted
already is that the castclass instruction generates an exception when no
cast exists while the isinst just places a null value on the evaluation
stack.
The implication is that if you know -- or expect your type to always be
castable then the castclass instruction provides some runtime safety in
case an unexpected value comes through -- and you dont suffer the
penalty of spinning up an exception. If, on the other hand, you are not
sure what the type will be, and you want to handle it gracefully, then
isinst allows you to avoid the performance penalties of an exception if
the class cannot be cast.
Dave wrote:
What is the benefit of using "as" vs the other?
HttpWebRequest myReq
= (HttpWebRequest)WebRequest.Create("http://www.contoso.com/");
vs.
HttpWebRequest myReq = WebRequest.Create("http://www.contoso.com/") as
HttpWebRequest;
Based on the MS documenation "The as operator is like a cast except that it
yields null on conversion failure instead of raising an exception. "
I've read some internal coding standards that state "Use the as operator to
defensively cast to a type", but I don't quite get the benefit of this and
want an outside opinion.
Thanks.