Author Topic: As operator without a null check  (Read 1474 times)

0 Members and 1 Guest are viewing this topic.

Jeff H

  • Needs a day job
  • Posts: 6150
As operator without a null check
« on: January 21, 2013, 12:25:56 PM »
Do you find code using 'as' operator without a null check buggy?


Not only do you trade a better telling InvalidCastException for a NullReferenceExeption, but using the as operator your code is saying you are not exactly sure what you are casting to.




Just wondering your thoughts and sure I am guilty of posting examples of using as operator with no null check.

MexicanCustard

  • Swamp Rat
  • Posts: 705
Re: As operator without a null check
« Reply #1 on: January 21, 2013, 01:45:40 PM »
I use ReSharper, so I get a warning anytime I use "as" and do not check for null.
Revit 2019, AMEP 2019 64bit Win 10

TheMaster

  • Guest
Re: As operator without a null check
« Reply #2 on: January 22, 2013, 05:59:10 AM »
Do you find code using 'as' operator without a null check buggy?


Not only do you trade a better telling InvalidCastException for a NullReferenceExeption, but using the as operator your code is saying you are not exactly sure what you are casting to.




Just wondering your thoughts and sure I am guilty of posting examples of using as operator with no null check.

The general rule I've always followed is to use 'as' when I want to know if the object is an instance of the type, and/or when I will use it as that afterwords, but is not an error if the object isn't an instance of the type.

I use a cast when the object must be of the type being cast to, or its an error.

I pretty much always do a null check after 'as', which is what you're supposed to do.

An InvalidCastException is not a hardware exception. A NullReferenceExeption is a hardware exception, and that seems to be why AutoCAD sometimes dies when they happen.


BlackBox

  • King Gator
  • Posts: 3770
Re: As operator without a null check
« Reply #3 on: January 22, 2013, 11:16:37 AM »
I use ReSharper, so I get a warning anytime I use "as" and do not check for null.

Resharper (or any add-in) will not work with Visual Studio Express.  :| *kicks dirt*
"How we think determines what we do, and what we do determines what we get."