Can anyone tell me whether isinst and castclass are internally using the
same mechanisms to determine type compatibility.  Does anyone have insights
about which one is more performant?  From what I've gathered from it's a
linear search through the type hierarchy when checking for type
compatibility.  I assumed that up until the point where the type is
determined to be compatible that these opcodes used the same internal
mechanism to do the check.  However, I did notice that the "as" operator in
C# doesn't take into account (at least it won't compile) explicit cast
overloads.

This question stems from a recent discussion with a colleague about which
was faster between the two:
======================================================
// Example 1

Base b = new Derived();

// Throws an exception if not of type Derived
Derived d = (Derived)b;

// Do some work with d

------------------------------------------------------
// Example 2

Base b = new Derived();

// Put a null reference on the stack if not of type Derived
Derived d = b as Derived;

if (d != null)
{
        // Do some work with d
}
else
{
        throw new InvalidCastException();
}
========================================================

For the sake of discussion, let's assume that if the cast would failed the
exception that is desired to be thrown is the type of
InvalidCastException().  Let's also assume that the cast is not known to
succeed.  Certainly example two is more explicit and conveys more visually
about what will happen when the operation fails.

Thanks
Fred Palmer

===================================
This list is hosted by DevelopMentor�  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to