1,105,546 Community Members

Gotchas in String.Compare Method

Member Avatar
Reputation Points: 25 [?]
Q&As Helped to Solve: 22 [?]
Skill Endorsements: 4 [?]

Have you ever tried using the String.Compare method for a case-insensitive string comparison?

The documentation on MSDN for the overloaded method:

Public Shared Function Compare ( _
    strA As String, _
    strB As String, _
    ignoreCase As Boolean _
) As Integer

Compares two specified String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order.

At first glance, this looks like exactly what we want, doesn't it?

There's a catch... look at the documentation again, especially the last phrase
and returns an integer that indicates their relative position in the sort order

The integer value returned is 0 if the strings are equal, if you try to use this comparison in an If statement the return value is False.

For example:
dim stringA as String = "lowercase", stringB as String = "Lowercase"
String.Compare(stringA, stringB, True)
returns 0, which is a Boolean False.

There is a solution! String.Equals to the rescue!

stringA.Equals(stringB, StringComparison.OrdinalIgnoreCase)
returns True - As an added benefit, this is already a Boolean value!

There are lessons to be learned here:

  • Always, always, always, read the documentation! (ReadTheFineManual)
  • When you think you understand what it says, go read it again, write some example code and step through that code
  • When your code doesn't "behave" - go read the docs again...
'simple console app, no imports needed
Module myStringComparison

    Sub Main()
        Dim myStringA As String = "Lowercase"
        Dim myStringB As String = "lowercase"
        Console.WriteLine("Using case-insensitive String.Compare method, are " & Chr(34) & "lowercase" & Chr(34) & Chr(32) & Chr(34) & "Lowercase" & Chr(34) & " the same string?")
        Console.WriteLine(CStr(CBool(String.Compare(myStringA, myStringB, True))))
        Console.WriteLine("Using case-insensitive String.Equals method instead, are " & Chr(34) & "lowercase" & Chr(34) & Chr(32) & Chr(34) & "Lowercase" & Chr(34) & " the same string?")
        Console.WriteLine(CStr(myStringA.Equals(myStringB, StringComparison.OrdinalIgnoreCase)))
    End Sub

End Module
Member Avatar
Newbie Poster
16 posts since Mar 2010
Reputation Points: -2 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]

Good point! Although I would reiterate what I've read about the difference with .Net -- Boolean true/false is not the same as integer 1/0. Same thing happened to me, except I was scanning for a substring in a string. Made my own function to return T/F on condition found or not. Really helps streamline your code to wrap up the conditional logic into a function and call it from an If statement.

Start New Discussion
View similar articles that have also been tagged: