Thursday, July 14, 2011

C# : Direct type casting versus 'as' keyword

A quick post about type casting with ( ) versus the as keyword in C#. The main difference between the two casting method is mainly the way it behaves when casting fails.

An example of direct casting with ( ):

void Fun(object obj)
  Foo f = (Foo) obj;

When you cast this way, if obj fails to cast to type Foo it will throw an InvalidCastException.You should always have a try-catch around this to catch exceptions.

Here's an example of casting with as:

void Fun(object obj)
  Foo f = obj as Foo;

In this case, if obj fails to cast to type Foo, f is assigned to null. This also means you should always write code to check/handle the null case after casting with as. Otherwise, it might later bubble up as a generic-hard-to-debug NullReferenceException (which is not as obvious as a InvalidCastException from direct casting). Another note, because it has to be able to assign null to the final object, this type of casting cannot be applied to basic types (e.g. int, byte, bool).

In most cases, if you know the type that obj should be cast to and don't expect the casting to fail, direct casting is preferred. This makes the problem more obvious whereas casting with as keyword may swallow your mistakes and make problems harder to debug later. This being said, as long as you handle the null case then it is ok to cast with as

Happy coding!

1 comment:

  1. Good post Annie!

    The pattern I follow is this:
    If you *know* the type of the target object, meaning you expect it to be of a specific type, use the direct cast. If it is not of that type, you'll get an exception, which makes sense since the target type wasn't what you expected.

    If you are unsure of the type of the target object, e.g. it could be one of many and you're trying out several, use 'as' since it is a normal use case for the 'as' cast to fail along your journey of finding the proper type.

    Thanx for dusting the spiderwebs off this ol' blog!