Comparing text values

Case-insensitive comparison

All text comparison is case-insensitive by default. This means that text such as “Hello”, “HELLO”, “hello” and “hELLO” are all treated the same when you compare using the comparison operators (=, <, >, <>, <=, >=).

If "Hello" = "hello" Then
  MessageBox("They match!") ' Displayed
End If

If "Hello" <> "hello" Then
  ' Not displayed
  MessageBox("They do not match.")
End If

Case-sensitive comparison

When you need to do case-sensitive text comparisons on String data, then use the String.Compare function to test the text values. Compare takes three parameters (other, compare and locale) and returns an Integer value indicating the result of the comparison.

The compare parameter indicates the type of comparison to do and uses the ComparisonOptions enumeration. When the value CaseInsensitive is used, the comparison is done without considering the case of the letters.

When the value CaseSensitive is used, the comparison is done using the case of the letters. For example, “Hello” and “HELLO” would be different strings because they are the same other than the case. However, it does mean that text such as “hello” and “Today” may not compare exactly how you would expect. In the strictest sense, “hello” is greater than “Today” because “h” has a higher character code than “T”. But with CaseSensitive, that detail is not used because the two strings are not the same.

Here are some examples:

Var source As String = "Hello"
If source.Compare("hello", ComparisonOptions.CaseInsensitive) = 0 Then
  MessageBox("They match!")
End If

If source.Compare("hello", ComparisonOptions.CaseSensitive) <> 0 Then
  MessageBox("They do not match.")
End If

See also

String data type; String.Compare function