Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most appropriate way to compare a string to a stringable object by value?

With this:

if (args.Parameter == "ContactIntermediaryPage")

...in a NavigatedTo() event handler, Resharper tells me: "Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'"

So should I change it to one of the following, and, if so, which one:

if ((string)args.Parameter == "ContactIntermediaryPage")

if (args.Parameter.ToString() == "ContactIntermediaryPage")

if (args.Parameter.Equals("ContactIntermediaryPage"))
like image 303
B. Clay Shannon-B. Crow Raven Avatar asked Oct 22 '22 22:10

B. Clay Shannon-B. Crow Raven


2 Answers

I would choose third one, making it also case insensitive (if this is suitable in your case)

if (args.Parameter.ToString().Equals(
               "ContactIntermediaryPage", 
                StringComparsion.InvariantCultureIgnoreCase))

In other words, if you're comparing to a string make left part of equation a string, to make clear to a compiler and to a reader of your code, what you're going to do on that line.

like image 134
Tigran Avatar answered Oct 26 '22 23:10

Tigran


the first one if args.Parameter is always a string. It saves an extra call.

otherwise the second one if, and only if, all possible strings are within your code. If so, I would define the strings as constants and reference them in one place if possible.

If neither of the above are true, then go for Tigran's answer.

like image 29
AndyD Avatar answered Oct 26 '22 22:10

AndyD