• Saves Valuable Time
  • Trusted Accuracy Since 2004
  • 15-Day Money-Back Guarantee

VB String Strangeness

VB programmers often mention that the 'String' type acts more like a value type than a reference type, but much of this confusion is a result of the VB compiler bypassing the .NET System.String equality/inequality operators. There is not as much confusion about System.String in other .NET languages, such as C#.

Although you might expect that the .NET System.String equality and inequality operator logic is used when you code in VB.NET, the Visual Basic compiler bypasses these operators completely. Instead, the VB compiler calls the Microsoft.VisualBasic.CompilerServices.Operators.CompareString method directly.

This is explained by Microsoft, about half way down on each of the following pages:
String.Equality Operator
String.Inequality Operator

The Microsoft.VisualBasic.CompilerServices.Operators methods handle empty strings and 'Nothing' in VB-unique ways totally separate from the logic defined within the .NET System.String class. For example, a null string (a string set to 'Nothing') is oddly regarded by VB as equal to an empty string and an empty string is oddly regarded as " = Nothing", but not " Is Nothing". The String type is the only reference type where VB allows you to use 'Nothing' with equality operators as if you were dealing with a value type (such as 'Integer') in addition to using it with 'Is' and 'IsNot' as you would for any other reference type.

When you are using '=' or '<>' on strings within VB, the .NET String class logic is ignored and the VB-specific logic takes over.

Dim s1 As String = Nothing
Dim b1 = s1 Is Nothing    'true (identical to " == null" in C#)
Dim b2 = s1 = Nothing    'true (but why is 'String' the only type that needs 2 ways of comparing to 'Nothing'?)
Dim b3 = s1 = ""            'true (VB weirdness)

Dim s2 As String = ""
Dim b4 = s2 Is Nothing    'false (identical to " == null" in C#)
Dim b5 = s2 = Nothing    'true (VB weirdness – if "Is Nothing" is false, how is it intuitive that "= Nothing" is true?)
Dim b6 = s2 = ""            'true

The designers of VB.NET made 2 clear mistakes:
1. They should have allowed '=' and '<>' to invoke the standard .NET string operator overloads instead of VB-specific logic.
2. They should have not allowed " = Nothing" and " <> Nothing" for strings – strings are reference types, so you should get the same error message that you would get if you tried this with any other reference type.

This might have broken some VB6 code being upgraded to VB.NET, but a lot of VB6 code was broken anyway in VB.NET. Having eccentric string behavior over the remaining life of VB.NET imposes a higher overall cost on VB programmers in terms of misunderstanding and confusion.

Copyright © 2004 – 2024 Tangible Software Solutions, Inc.