Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CA1307: Specify StringComparison not thrown for string.Equals(string)

I am wondering why the static code analysis (of VS 2015) will not lead to an error if you use String.Equals(string). So

"file".Equals("FILE")

does not lead to code analysis error, whereas

String.Compare("file", "FILE", true)

does lead to CA 1307 error.

The documentation for this rule says on MSDN

Many string operations, most important the Compare and Equals methods, provide an overload that accepts a StringComparison enumeration value as a parameter.

Whenever an overload exists that takes a StringComparison parameter, it should be used instead of an overload that does not take this parameter. By explicitly setting this parameter, your code is often made clearer and easier to maintain.

From this I would expect that the first example should lead to CA 1307 error.

So not throwing the error in that case could be very dangerous in some cases and lead to a "buggy" applications.

Am I missing something here?

If this is by design, is there any way that I can achieve the expected behaviour?

like image 936
donttellya Avatar asked Sep 18 '26 04:09

donttellya


1 Answers

Your compare method you are passing a boolean whereas the Compare function is expecting a StringComparison enum value.

String.Compare("file", "FILE", StringComparison.InvariantCultureIgnoreCase);

This should return a true response because you are ignoring case.

like image 197
Chad Avatar answered Sep 20 '26 19:09

Chad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!