Add watch window shows value but the value is not assigned to variable

Viewed 85

The below code when checked in "Add watch" window shows the right value (100), but the value is not assigned to variable _countVar, the value is 0 which is incorrect.

Can someone tell me what is wrong in my code:

string _strVariable = "New York";

var _countVar = nestList
  .SelectMany((List<object> w) => w)
  .Count(w => w == _strVariable);
1 Answers

Well, if w is of type object in

...
.SelectMany((List<object> w) => w) // w is object
.Count(w => w == _strVariable);    // if w has the same reference as _strVariable

you actually compare references, not strings values. If strings don't share the same reference (they are not Interned), they will be considered different:

object x = "abc";

// some manipulations to prevent the compiler to intern x and y strings
string y = ("abc" + " ").Trim(); // "abc", note that y has the same value as x

Console.Write(x == y ? "equals" : $"{x} <> {y}");

Outcome:

abc <> abc

To compare strings values put string.Equals:

string _strVariable = "New York";

var _countVar = nestList
  .SelectMany(list => list)
  .Count(city => string.Equals(city, _strVariable));
Related