Comparing the equality of two strings is typically considered a simple matter. Programmers vary in their preference among five choices:
The first two choices are essentially the same choice. If the compiler detects that both sides of the equality operator are strings, the operation equates to String.Equals. String.Equals performs a case-sensitive, culture-insensitive comparison: string s1 = "Bob"; string s2 = "BOB"; if (String.Equals(s1, s2)) textBox1.Text += "Equal" + System.Environment.NewLine; else textBox1.Text += "Not Equal" + System.Environment.NewLine; string s3 = "Bob"; string s4 = "Bob"; if (String.Equals(s3, s4)) textBox1.Text += "Equal" + System.Environment.NewLine; else textBox1.Text += "Not Equal" + System.Environment.NewLine; In this example, "Bob" does not equal "BOB" because they are different cases. "Bob" does equal "Bob" because their values are the same. This shows that String.Equals tests the values of strings, not the references of string, so although s3 and s4 have different references, they have the same value. The third, fourth, and fifth choices are also the same if a test for equality is your only desire. These three methods return an integer, where 0 means that the two strings are equal. Although the return results will vary according to the given culture if the strings are not equal, the results will not vary, regardless of culture, if the two strings are exactly equal. Consequently, a comparison with 0 will always be accurate, regardless of cultural considerations. The difference between these methods and the meaning of nonzero return results are covered in the section entitled "Sort Orders." |