by Jim
Jan 01, 2009 9:24 PM
It’s code review time!
The as operator is not the same thing as a cast. It is not better, it is different. It is appropriate in some situations, but not in others. Some people us it because they prefer the syntax, but it does different things, and the two are NOT interchangeable.
Using the as operator differs from a cast in C# in three important ways:
- It returns null when the variable you are trying to convert is not of the requested type or in its inheritance chain, instead of throwing an exception.
- It can only be applied to reference type variables converting to reference types.
- Using
as will not perform user-defined conversions, such as implicit or explicit conversion operators, which casting syntax will do.
Number three is a good enough reason to prefer the cast as a general rule. By using the as operator you may be circumventing functionality that someone intentionally put into the class you’re referencing!
Here is a hard and fast rule for you:
IF YOU AREN’T GOING TO CHECK FOR THE NULL, DON’T USE THE as OPERATOR.
If there is a bug that results in the type you’re converting being the wrong type, you’ll get a null reference exception – possibly in code that is far from the as operator you used. Someone will have to debug that one day. And they’re going to waste time trying to figure out why the value is null, when they really need to be trying to figure out why the value is of the wrong type.
If you’re going to assume that the object is of a particular type, use the direct cast. This will result in an invalid cast exception, which is informative, and happens right there at the cast. The stack trace and the error message will tell someone precisely what happened and where:
System.InvalidCastException: Unable to cast object of type 'Foo' to type 'Bar'.
Now we know what went wrong – a NullReferenceException doesn’t tell us that.