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

Is it good to compare strings with == ? Is there an equivalent s1 == s2 in terms of the Compare and Equals methods on string . If you use these methods, without specifying CultureInfo FxCop will give a warning, is this a real problem?

+6
source share
5 answers

The == operator is an ordinal, cultural operator that does not know the comparison string. It uses the same internal call as .Equals , and is great for "regular" string comparisons.

If you need cultural comparisons (e.g. for GUI purposes) like German double or ß, use

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

When comparing strings, you should use methods that explicitly indicate which comparison you intend to perform. This makes your code much more convenient and readable. If possible, use the overloads of the methods of the System.String and System.Array classes that take the StringComparison enumeration parameter so that you can specify what type of comparison to perform. It is better to avoid using the == and! = Operators when comparing strings. Also avoid using instance methods of String.CompareTo, because none of the overloads accepts the StringComparison parameter.

Depending on your needs, you can use the following 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

+2
source

There is extensive documentation on MSDN that talks about ordinal and cultural string comparisons. Ordinary comparisons do not care about linguistics and, by default, will concern matters. Culturally sensitive comparisons really care about linguistics (cases, shortening, etc.).

This article in dotnetperls takes a look at performance implications and even shows IL and benchmarks for two string comparison methods ( == and equals ).

And finally, this question shows that == is strictly ordinal string matching and not suitable for localized strings.

+2
source

Yes, this practice is wonderful. You can also use String.Compare , and a comparison is best found in Best Pratices to use strings in the .NET Framework .

Yes, FxCop will give warnings, but warnings will give warnings. If you don’t care about culture, you can ignore them. But, like warnings about real life, sometimes you have to listen to them.

+1
source

If the string can be empty or empty (aka ""), you want to use string.IsNullOrEmpty (...);

Otherwise, it’s fine in my book or most of the things. Depends on what you do.

+1
source

Source: https://habr.com/ru/post/901839/


All Articles