简体   繁体   中英

Is it good practice to compare C# string with '=='?

Is it a good practice to compare strings with == ? Is there an equivalent to s1 == s2 in terms of Compare and Equals methods on string . If one uses those methods, without specifying CultureInfo FxCop will give a warning, is that a real problem?

The == Operator is an ordinal, culture unaware string compare. Its using the same internal call as .Equals , and is just fine for the "usual" string compare stuff.

If you need Culture-Aware comparings (eg. For GUI purposes ) , like german double-s or ß, use

CultureInfo ci = new CultureInfo("de-DE");
String.Compare("Strasse", "Straße", true, ci)

When you compare strings, you should use the methods that explicitly specify what kind of comparison you intend to perform. This makes your code much more maintainable and readable. Whenever possible, use the overloads of the methods of the System.String and System.Array classes that take a StringComparison enumeration parameter, so that you can specify which type of comparison to perform. It is best to avoid using the == and != operators when you compare strings. Also, avoid using the String.CompareTo instance methods because none of the overloads takes a StringComparison.

Depending on your needs, you can use on of the next methods:

bool result = root.Equals(root2, StringComparison.Ordinal);
result = root.Equals(root2, StringComparison.OrdinalIgnoreCase);
bool areEqual = String.Equals(root, root2, StringComparison.Ordinal);

Source for this answer: http://msdn.microsoft.com/en-us/library/cc165449.aspx

There is extensive documentation on MSDN that talks about ordinal and culture-sensitive string comparisons. Ordinal comparisons do not care about linguistics and, by default, will be concerned with case. Culture-sensitive comparisons do care about linguistics (cases, puncutation, etc).

This article on dotnetperls digs into the performance implications and even shows IL and benchmarks for the two methods of string comparison ( == and equals ).

And, finally, this question shows that == is strictly an ordinal string comparison and not appropriate for localized strings.

Yes, that practice is fine. You can also use String.Compare , and the comparison best practies found in Best Pratices for Using Strings in the .NET Framework .

Yes, FxCop, will give warnings, but warnings are warnings. If you don't care about culture it's safe to ignore them. But, like real life warnings, it sometimes pays to heed them.

If a string might be null or empty(aka "") you want to use string.IsNullOrEmpty(...);

Otherwise its fine in my book or most stuff. Depends on what your doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM