November 2009 Blog Posts

‘as’ is no safer than cast without a null check

I’ve recently encountered code which looks something like: var someInstance = someParameter as ISomething; someInstance.DoSomething();   The problem with this code is that it is wide open for a highly unhelpful NullReferenceException. If someParameter cannot be cast to ISomething the as operator will return null. But this code doesn’t check if someInstance is null. It makes the assumption that someParameter may be case to ISomething, even though in practice this assumption may not hold. There are two solutions to this. You may replace the use of the as operator with an explicit cast. This will throw an InvalidCastException if the cast cannot be...

posted @ Tuesday, November 03, 2009 3:44 PM | Feedback (2)