Tuesday, November 6, 2007

Replace With Direct Cast

An instance of the as operator should always be followed by a check against null.

Customer customer = obj as Customer;

if(customer != null){

If you don't want to check against null than refactor to a direct cast.

(obj as customer).Update;

If the direct cast fails you will get an InvalidCastException instead of a NullReferenceException which will be easier to diagnose.

1 comment:

Englestone said...

Great tip.

Resharper is forever reminding me of this!

-- Lee