Check if String is Empty

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
 
A

Aidy

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.
 
C

Cowboy \(Gregory A. Beamer\)

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top