Who's Afraid of the big-bad cast operator?

My previous blog entry (which was completely misunderstood by some people who commented - I blame the fact that English is not my native tongue) reminded me of another poor coding behavior. Just so we don't have a repeat of that last post, let me clarify that I have nothing against the as operator - I use it all the time - I just have a problem with certain usage patterns that employ it.

For whatever reason, people tend to use the "as" operator instead of the cast operator.

A lot of times you will see code like this:

 MyClass c = o as MyClass;

Where the following code makes MUCH more sense:

 MyClass c = (MyClass)o;

I have two theories as to why people do it this way:

1. People are afraid of Exceptions.
2. People are used to dynamic_cast<>() from C++ which is the easiest way to check if a class is of a certain runtime type.

The reason the example above with the"as" operator is a Bad Thing is because it defers the exception to a later point in your code. If the class is not what you expect it to be, your cast will succeed (resulting in NULL) only to fail a few lines later on a NullReferenceException - which in turn makes debugging and logging harder to understand because you are not really seeing the correct exception.

Now, there are many valid usages of the as operator - but they almost always rely on the fact that you actually do something with the fact that the class is different than what you expect. So for example, if you want your Equals method to be able to handle classes different than your own, that's a GREAT place to use as:

 public override bool Equals(object o)
    MyClass other = o as MyClass;
    if (other == null) return false;

However, if you do not intend for your .Equals method to support comparison with other types (and have no other usage for the knowledge that the reference you got is not what you expected), you should definitely useĀ  the regular cast operator.