Check if String is Empty

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I need to check if a string is empty.

Should I use:

String.IsNullOrEmpty(MyString) or MyString Is Nothing?

What is the difference?

Thanks,
Miguel
 
Hello,
I need to check if a string is empty.

Should I use:

String.IsNullOrEmpty(MyString) or MyString Is Nothing?

What is the difference?

Thanks,
Miguel

A string variable can point to Nothing (ie be unassigned). Although it is
possible to have Nothing string vars, you are supposed to give empty string
values the special value of String.Empty rather than leaving them point to
Nothing.

Dim myString as String = Nothing ' Wrong
Dim myString as String = String.Empty ' Right

The "MyString Is Nothing" only checks of the string is pointing to Nothing
(ir not initialised). The IsNullOrEmpty checks if the string is Nothing, or
if it contains String.Empty as a value.
 
I like

If (stringName.Length > 0) Then
'String is not nothing
Else
'String is empty
End If

The above is relatively fast. You can also Trim() if you are not sure the
string is not full of spaces:

If (textBoxName.Text.Trim().Length > 0) Then
End If

There are a variety of ways to do this:

If Not (stringName = String.Empty) Then

etc.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
http://gregorybeamer.spaces.live.com

********************************************
Think outside the box!
********************************************
 
Back
Top