views:

127

answers:

1

I'm still trying to map my deep and old knowledge from C/C++ to my somewhat more shallow .Net knowledge. Today the time has come to "as" (and implicitly "is" and cast) in C#.

My mental model of "as" is that it's a QueryInterface or dynamic_cast (a dynamic_cast with pointer argument, not reference, that is) for C#. My question is two-fold:

  1. Is my comparison fair?
  2. What's the relative cost of "as" compared to QueryInterface or dynamic_cast?
+4  A: 
  1. Yes, the comparison is fair, especially when dealing with pointers. Each of the three either succeeds and returns a non-null pointer of the target type, or returns null.

  2. You can actually use the as operator when working with COM objects in .NET, making it equivalent to QueryInterface with a small amount of overhead for the managed/COM interop. Inside of the CLR (casting between managed types), the as operator is extremely lightweight compared to QueryInterface in COM or dynamic_cast in C++. For all the places in my code where I had to use dynamic casting for some reason, I've never seen the as operator show even one sample in profiling - and considering I maintain an implementation of a dynamically-typed, runtime-bound language (StringTemplate), I assume that means something. :)

280Z28