IsNothing versus Is Nothing

后端 未结 9 1517
暗喜
暗喜 2020-11-29 23:51

Does anyone here use VB.NET and have a strong preference for or against using IsNothing as opposed to Is Nothing (for example, If IsNothing(a

9条回答
  •  再見小時候
    2020-11-30 00:14

    You should absolutely avoid using IsNothing()

    Here are 4 reasons from the article IsNothing() VS Is Nothing

    1. Most importantly, IsNothing(object) has everything passed to it as an object, even value types! Since value types cannot be Nothing, it’s a completely wasted check.
      Take the following example:

      Dim i As Integer
      If IsNothing(i) Then
         ' Do something 
      End If
      

      This will compile and run fine, whereas this:

      Dim i As Integer
      If i Is Nothing Then
          '   Do something 
      End If
      

      Will not compile, instead the compiler will raise the error:

      'Is' operator does not accept operands of type 'Integer'.
      Operands must be reference or nullable types.

    2. IsNothing(object) is actually part of part of the Microsoft.VisualBasic.dll.
      This is undesirable as you have an unneeded dependency on the VisualBasic library.

    3. Its slow - 33.76% slower in fact (over 1000000000 iterations)!

    4. Perhaps personal preference, but IsNothing() reads like a Yoda Condition. When you look at a variable you're checking it's state, with it as the subject of your investigation.

      i.e. does it do x? --- NOT Is xing a property of it?

      So I think If a IsNot Nothing reads better than If Not IsNothing(a)

提交回复
热议问题