24

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

Dim strTest As String
If (strTest.IsNullOrEmpty) Then
   MessageBox.Show("NULL OR EMPTY")
End if
CJ7
  • 22,579
  • 65
  • 193
  • 321
  • 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. – sloth Oct 30 '12 at 07:40

3 Answers3

71

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

If String.IsNullOrEmpty(strTest) Then
Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Tomq
  • 1,085
  • 11
  • 14
10

You can actually just compare to an empty string:

If strTest = "" Then
    MessageBox.Show("NULL OR EMPTY")
End If
Rolf Bjarne Kvinge
  • 19,253
  • 2
  • 42
  • 86
  • 1
    What if `strTest` is `nothing`? `IsNullOrEmpty` explicitly contains a check whether `strTest` is `nothing`. Your statement does not check this. – Thorsten Dittmar Oct 30 '12 at 14:05
  • 7
    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: http://stackoverflow.com/questions/2633166/nothing-string-empty-why-are-these-equal – Rolf Bjarne Kvinge Oct 30 '12 at 16:06
  • +1 @ThorstenDittmar, Rolf is right on this one. VB.Net treats `Nothing` as identical `""` when doing string comparisons (and in other places too). – MarkJ Oct 30 '12 at 17:08
  • @MarkJ: Sorry, didn't know that. Tried to undo my downvote, but SO won't let me unless the answer is edited...? – Thorsten Dittmar Oct 31 '12 at 07:46
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
moribvndvs
  • 42,191
  • 11
  • 135
  • 149
  • When I do that it says that a NullPointerException could be raised at runtime. – CJ7 Oct 30 '12 at 07:39
  • 1
    @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`. – sloth Oct 30 '12 at 07:41
  • @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 Oct 30 '12 at 08:10
  • 1
    @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. – sloth Oct 30 '12 at 08:17