Search code examples
vb.nettcptcpclient

Check if TcpClient was not called -X IsNot Nothing vs Not X Is Nothing [vb.net]


How do I check if the function has defined TcpClient before? I'm using a Sub to open a connection and a timer to check if the connection is still alive ( using the same Sub!).

Public clientTest as TcpClient = nothing

Sub OpenCheckConnection()
  If clientTest is not Nothing AndAlso clientTest.Connected = True Then
     pictureboxTest.Image = xxGreen
  Else
     clientTest = New TcpClient
     Try
       clientTest.Connect(IPtest, Porttest)
     Catch ex As Exception
       NewLog(ex.ToString)
     End Try
'
      If clientTest.Connected = True Then
      (...)                 '
      Else
         pictureboxTest.Image = xxRed
      End If
  End If
End Sub

I've tested this and clientTest is not Nothing is not defined for TcpClient. "clientTest <> 0 is not defined as well. How can i manage this?


Solution

  • IsNot. One word:

    If clientTest IsNot Nothing ...
    

    Alternatively, you can write this:

    If Not (clientTest Is Nothing) ...
    

    Nothing for reference types is a special value, and negating it directly via a logical Not doesn't help you. A logical Not of an unknown value is still an unknown value.

    Instead, you want either the IsNot logical inverse for the Is operator, or just the Is operator where you place the logical Not to negate the entire boolean expression.