Cache the result of the ‘as’ operator or direct cast in order to eliminate the redundant castclass instruction

To understand why you’re getting this error requires that you understand the different ways .NET can do casting. First off, let’s talk about the C# "as" operator described in the FxCop rule resolution. The C# "as" operator will attempt a cast and return null if it fails — instead of raising an InvalidCastException. The "as" operator uses the "isinst" IL instruction. There is no equivalent in the current version of VB.NET. VB.NET 2005 will have a "TryCast" which will do the same thing as the C# "as" operator.

When it comes to regular casting in C# (or the "DirectCast" statement in VB.NET), the IL "castclass" instruction is used. This one will attempt a cast and raise an InvalidCastException if it can’t perform the cast. So the two opcodes perform the same thing, but they operate differently: the "isinst" is a cast that doesn’t throw an exception and "castclass" is a cast that will throw an exception.

The reason you see a warning from FxCop in the code above is because the VB.NET "TypeOf" operator uses the "isinst" instruction. That’s one cast that FxCop sees. And then the DirectCast compiles into a "castclass" instruction. So FxCop sees your code doing another cast on the same set of variables. Casting isn’t cheap so FxCop recommends you cache the result of the "as" operator (C# only) like so:

Module1 m = x as Module1;
if( m != null )

Or, if you are using delegates with AsyncCallback terminolgy.Cast the object this way,

AsyncResult ar = (AsyncResult)result;
object objDelegated = ar.AsyncResult;
ObjType1 m_obj1 = objDelegated as ObjType1;
ObjType2 m_obj2 = objDelegated as ObjType2;
ObjType3 m_obj3 = objDelegated as ObjType3;

if (m_obj1 != null) {….}
if (m_obj2 != null) {….}
if (m_obj3 != null) {….}


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Blog at

Up ↑

%d bloggers like this: