String equality comparison
Despite ordinal’s limitations, string’s == operator always performs ordinal case-
sensitive comparison. The same goes for the instance version of string.Equals when
called without arguments; this defines the “default” equality comparison behavior
for the string type.
The ordinal algorithm was chosen for string’s == and Equals
functions because it’s both highly efficient and deterministic.
String equality comparison is considered fundamental and is
performed far more frequently than order comparison.
A “strict” notion of equality is also consistent with the general
use of the == operator.
The following methods allow culture-aware or case-insensitive comparisons:
public bool Equals(string value, StringComparison comparisonType);
public static bool Equals (string a, string b,
StringComparison comparisonType);
The static version is advantageous in that it still works if one or both of the strings
are null. StringComparison is an enum defined as follows:
The static version is advantageous in that it still works if one or both of the strings
are null. StringComparison is an enum defined as follows:
public enum StringComparison
{
CurrentCulture, // Case-sensitive
CurrentCultureIgnoreCase,
InvariantCulture, // Case-sensitive
InvariantCultureIgnoreCase,
Ordinal, // Case-sensitive
OrdinalIgnoreCase
}
For example:
Console.WriteLine (string.Equals ("foo", "FOO",
StringComparison.OrdinalIgnoreCase)); // True
Console.WriteLine ("?" == "u"); // False
Console.WriteLine (string.Equals ("?", "u",
StringComparison.CurrentCulture)); // ?
(The result of the final comparison is determined by the computer’s current language
settings.)
No comments:
Post a Comment