Links

Current series

Visitors

Blogged

Technorati

Casts using “as” (Pitfalls and Best Practices to Prevent Them #5)

November 27, 2009 — winsharp93

Well – “as” is faster to type than a “real” cast using two brackets and has the same result. Really?

C# provides several ways to cast one type to another one. The two used in most cases are the “([Targettype]) [Variable]” and the “[Variable] as [Targettype]” notations. Many developers see them as equivalents, some even prefer “as” because it does not throw an exception when the cast fails.

Example

Let’s say we have a variable called obj of type Object and we want to cast it to an IFoo so we can call IFoo.Bar:

object obj;
//...
(obj as IFoo).Bar();

What does it do?

In line we are using as to cast obj to type IFoo as we can not call this method directly on an Object.

What does it actually do?

Well – it works great…

…as long as obj can be converted to IFoo. If not, however, there will occur a NullReferenceException even if obj is not null. You can try this by replacing the comment in line two with the following code:

obj = 53;

However, the real problem is not a null reference, but a failed cast. What we would expect is a InvalidCastException. So debugging is complicated considerably as we get a confusing error message. On the other hand, as could not avoid an exception what we might have thought when deciding to use it.