26

Why doesn't the following compile in VB.NET?

Dim strTest As String
If (strTest.IsNullOrEmpty) Then
   MessageBox.Show("NULL OR EMPTY")
End if
1
  • The compiler says: Argument not specified for parameter 'value' of 'Public Shared Function IsNullOrEmpty(value As String) As Boolean'., so you could guess it's because you didn't specify an argument for the parameter value of that method. What I want to say is that (most of the time) the compiler will tell you what's wrong with your code. Commented Oct 30, 2012 at 7:40

3 Answers 3

75

IsNullOrEmpty is 'shared' so you should use it that way:

If String.IsNullOrEmpty(strTest) Then
Sign up to request clarification or add additional context in comments.

Comments

11

You can actually just compare to an empty string:

If strTest = "" Then
    MessageBox.Show("NULL OR EMPTY")
End If

4 Comments

What if strTest is nothing? IsNullOrEmpty explicitly contains a check whether strTest is nothing. Your statement does not check this.
Actually it does, string comparison against an empty string will return true for Nothing too in VB. Try it out if you don't believe me. Or maybe this convinces you: stackoverflow.com/questions/2633166/…
+1 @ThorstenDittmar, Rolf is right on this one. VB.Net treats Nothing as identical "" when doing string comparisons (and in other places too).
@MarkJ: Sorry, didn't know that. Tried to undo my downvote, but SO won't let me unless the answer is edited...?
9

String.IsNullOrEmpty is a shared (or static, in C#) method.

Dim strTest As String
If (String.IsNullOrEmpty(strTest)) Then
   MessageBox.Show("NULL OR EMPTY")
End if

4 Comments

When I do that it says that a NullPointerException could be raised at runtime.
@CJ7 It's because you use strTest without setting a value (which could be a mistake), so it is always Nothing. You can get around it by using Dim strTest As String = Nothing e.g. to explicitly set it to Nothing.
@Mr.Steak: that seems a bit strange because if I don't set it to anything it will be Nothing anyway. Why should I have to explicitly set it to Nothing - doesn't make any sense!
@CJ7 Yes, it will be Nothing anyway, but since you didn't explicitly tell the compiler so, it just warns you that it could be a bug in your code (hence it's just a warning, not an error). Note that you can disable those warnings, but I would not recommend doing so.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.