Have you ever tried using the String.Compare method for a case-insensitive string comparison?
The documentation on MSDN for the overloaded method:
'Declaration 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.
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!
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() 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