Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding usages of string == operator in a large codebase

Tags:

c#

I've had a request to look into the feasibility of replacing all of the string == operator usages in a reasonably large C# codebase with String.Equals() method calls that explicitly specify case-sensitivity.

Haven't had much luck figuring out a way to identify all the occurrences in the codebase, though.

  • Searching for "==" obviously finds countless instances of types other than strings being compared.
  • There doesn't seem to be a StyleCop rule to find this.
  • Nor a ReSharper rule.
  • As a last resort I tried loading the assemblies into JustDecompile and finding all usages of System.String.op_Equality but that doesn't seem to pick up usages inside of LINQ expressions such as .Where(x => x.StringField == stringField)

So I'm a little stumped and wondered if anyone had any ideas on how to search these pesky comparisons out?

like image 555
Carson63000 Avatar asked Aug 01 '12 07:08

Carson63000


People also ask

How does == operator behave in case of string?

String comparison is a common scenario of using both == and equals method. Since java. lang. String class override equals method, It returns true if two String object contains same content but == will only return true if two references are pointing to the same object.

Can you use == for Strings in C++?

In C++ the == operator is overloaded for the string to check whether both strings are same or not. If they are the same this will return 1, otherwise 0. So it is like Boolean type function.

How does the == operator work?

The equal-to operator ( == ) returns true if both operands have the same value; otherwise, it returns false . The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .

Can we use != For string?

Note: When comparing two strings in java, we should not use the == or != operators. These operators actually test references, and since multiple String objects can represent the same String, this is liable to give the wrong answer.


1 Answers

You can use Resharper to find all the usages. Here's what works for me:

  1. Right click on the string type anywhere in your code. Click Go to Declaration.
  2. Resharper will open string.cs from the .NET framework
  3. Scroll down to operator == and right click, select Find Usages

It takes a bit of time but you'll get a nice list of usages, ordered in a tree view. I tried this with Resharper 6.1 in VS2010.

UPDATE

There is a simpler way to do this:

  1. Select == in a string comparison
  2. Right click on the selection and choose Find Usages Advanced
  3. In the dialog under find check only 'Usages' and set scope to 'Solution' to filter out any references in other libs.
like image 73
Marnix van Valen Avatar answered Oct 29 '22 15:10

Marnix van Valen