Strings and Equality

As fully explained in Chapter 12, a reference type is an object allocated on the garbage-collected managed heap. By default, when you perform a test for equality on reference types (via the VB 2008 = and <> operators), you will be returned True if the references are pointing to the same object in memory. However, even though the String data type is indeed a reference type, the equality operators have been redefined to compare the values of String objects, not their location in memory:

Module Program Sub Main()

Console.WriteLine("***** Fun with Strings *****")

Dim strA As String = "Hello!" Dim strB As String = "Yo!" ' False!

Console.WriteLine("strA = strB?: {0}", strA = strB) strB = "HELLO!"

Console.WriteLine("strA = strB?: {0}", strA = strB) strB = "Hello!"

Console.WriteLine("strA = strB?: {0}", strA = strB) End Sub End Module

Notice that the VB 2008 equality operators perform a case-sensitive, character-by-character equality test. Therefore, "Hello!" is not equal to "HELLO!", which is different from "hello!".

Was this article helpful?

0 0

Post a comment