VBNullString

Don McNamara points out this:

VB.NET

(nothing = String.Empty) is true

C#

(null == String.Empty) is false

Looks like another "mort feature"... that is what VBNullString is for :-). On the one hand, you can argue that it makes you more productive, because you can automatically test for both empty and null at the same time. On the other hand, it just doesn't feel right to have a special case null value. For instance, consider the following code:

foreach(object o in objects)
{
    if(o == null)  { /* do something */ }
}

Anyone know how you would do this in VB.NET?

Update: I figured it out:

for (i = 0 to objects.Count)
 if(IsNothing(objects.Item(i))) then
  'do something
 end if
next

but, if you do:

for (i = 0 to objects.Count)
 if(objects.Item(i) = Nothing) then
  'do something
 end if
next

Then you will get different results. Doesn't make too much sense in my mind...but that is why I code in a different language :-).

6 Comments

  • I use something like this for rows in a dataset:





    Dim O as Object





    For Each O In ObjectCollection


    If O Is Nothing Then


    ' Do Something


    End If


    Next

  • DataSets are a little different, because they use DBNull, not null, but still that code makes no distinction between null and empty, which is why "nothing" doesn't match C#'s "null".

  • In VB.NET (generically speaking), you use the Is operator to check for reference types and the = operator to check for value types (and strings). Of course, you could also use the .Equals() method associated with the object to do the same thing. :-)

  • This is interesing. I never even bothered to look at this differnce between the languages.





    In VB.Net:


    (nothing = string.emtpy) returns true


    ("" = string.empty) returns true





    (IsNothing(string.emtpy)) returns true


    (IsNothing("")) returns false





    (nothing is string.emtpy) returns false


    ("" is string.empty) returns true





    (string.emtpy.equals(nothing)) returns false


    (string.emtpy.equals("")) returns true





    ---------------





    When you look at the IL produced by the VB compiler, the equals operator with the string results in an additional call to strcmp. (C# does not call strcmp with the equals operator.)


  • blah blah blah



    That's all that I hear since I know no VBScript. (*sigh* I need to learn this)

  • Just Find Out:
    in Visual Studio 2003
    "" Is String.Empty --> true

    While in Visual Studio 2008
    "" Is String.Empty --> false

Comments have been disabled for this content.