IsNot usage & Nothing usage

ADO DOT NET

Centurion
Joined
Dec 20, 2006
Messages
160
Hi,
I have 2 questions:

1. I still didn't understand when I should use "" and when I should use Nothing?
For example, when checking the value of a text box or getting value from registry or etc... for which case I should use each one?

2. I also didn't found out the difference between <> and IsNot yet!
For example when comparing 2 values or comparing 2 checkboxes or etc...
When I should use <> and when I should use IsNot?!

Many thanks for your help to help me learn:)
 
It all has to do with "value" vs. "reference".

"" means that the String object exists, but contains an empty String. 'Nothing' means that the object has not yet been instantiated (with the New keyword). So, checking the value of a TextBox.Text, you would check for an empty String (""), since the Text parameter of a TextBox is instantiated when the TextBox is instantiated. You can always use both:

Visual Basic:
If someString IsNot Nothing AndAlso someString <> "" Then
'do something
End If

If the string was defined but not instantiated, e.g.:
Visual Basic:
Dim someString As String
If someString Is Nothing Then
'this would be True
End If
If someString = "" Then
'this would cause a run-time exception, since someString
'has not yet been instantiated
End If
 
'you could keep the runtime exception from happening by checking it like this:
If someString Is Nothing OrElse someString <> "" Then
'this would be True if either the someString object was not yet
'instatiated, or, if someString contains an empty string
End If
 
'it is generally a good idea to define a String this way to keep
'the runtime error from happening:
Dim someOtherString As String = ""
If someOtherString Is Nothing Then
'this would be False
End If
If someOtherString = "" Then
'this would be True
End If

'<>' means "the contents of the object are not equal to". 'IsNot' means "the variable names do not point to the same object in memory".

So,
Visual Basic:
If someString <> someOtherString Then
'the contents of someString do not equal the contents of someOtherString
End If
 
If someString IsNot someOtherString Then
'the variable name someString does not point to the same
'object in memory as the variable name someOtherString
End If

This may not explain everything, but I hope it points you in the right direction.

Todd
 
Last edited:
For question number 1, my recommendation: use the String.IsNullOrEmpty method. If the value is either null (Nothing in VB) or empty, then it will return true, covering all your bases.

My answer for question 2: == and <> compare the value of two objects. Is and IsNot compare to see if two variables hold the same object.
 
Back
Top