5

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"))
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • Is there any concern for the `null` case where `args.Parameter` is null? That can _definitely_ have a significant impact depending on which option you use. – Chris Sinclair Dec 17 '12 at 22:33
  • `if (args.Parameter.Equals("ContactIntermediaryPage"))` would not work - since it expects an object of type `Parameter` – Matt Roberts Dec 17 '12 at 22:42

2 Answers2

2

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.

Tigran
  • 61,654
  • 8
  • 86
  • 123
  • Prb stating the obvious, but just to add that you don't need the `InvariantCultureIgnoreCase` if you do care about case (it's always going to be in CamelCase. – Matt Roberts Dec 17 '12 at 22:49
1

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.

AndyD
  • 5,252
  • 35
  • 32