« Form Follows Function | Main | Prediction Markets: A better way to predict project outcome »

December 16, 2005

"Safe" casting isn't safe

C# has an operator -- as -- that has the common but Orwellian name of "safe casting:"

User user = aHashtable[ USER_NAME ] as User;
if( user.isAuthenticated ) {
// ...

I’ve worked at several places where they mandate that you use the as operator rather than the normal cast:

User user = (User) aHashtable[ USER_NAME ];
if ( user.isAuthenticated ) {
// ...

The problem is that using "safe" casting the first code snippet fails just as harshly as the second. Worse is that it fails with a NullReferenceException at some other point in the system. The example I've provided is a best case; the null reference could be used in a different method or class. Someone debugging would have to deduce that the problem occurred because of the "safe" cast.

Conversely, the second example fails clearly and cleanly with a InvalidCastException. A stack trace will point you directly to the offending line.

I strongly prefer using normal casting. It crashes early -- one of the Pragmatic Programmers’ principles.

Also, this is just one of many examples why strict coding standards generally hurt code quality more than they help.

Posted by gsmith at December 16, 2005 04:02 PM