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:
QueryInterface
or dynamic_cast
?The primary purpose for the dynamic_cast operator is to perform type-safe downcasts. A downcast is the conversion of a pointer or reference to a class A to a pointer or reference to a class B , where class A is a base class of B .
Yes, dynamic_cast is a code smell, but so is adding functions that try to make it look like you have a good polymorphic interface but are actually equal to a dynamic_cast i.e. stuff like can_put_on_board .
Consider this simple hierarchy: class Base { public: virtual ~Base() { } }; class Derived : public Base { }; Trying to downcast Base* p to Derived* is possible using dynamic_cast<Derived*>(p) . I used to think dynamic_cast works by comparing the vtable pointer in p to the one in a Derived object.
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.
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With