In each case, the second operand of ==
is x
, which is of type object
. That means you're using the normal reference equality operator.
Now in your first case, you're using two string constants with the same contents. The C# compiler will use a single object for those two references. In the second case, x
and y
refer to distinct string objects with the same contents. The two references will be different, so ==
will return false.
You can fix the comparison by:
Use Equals
instead - that's overridden by string
(as opposed to the ==
operator which is only overloaded:
Console.WriteLine(y.Equals(x)); // or x.Equals(y), or Equals(y, x)
The use of the static Equals(object, object)
method can be useful if either of the arguments can be null; it means you don't need to worry about a NullReferenceException
.
Make both variables of type string
, at which point the ==
overload within string
will be picked at compile-time, and that overload compares the contents of the strings, not just the references
It's worth noting that it's not just a matter of the string literals itself being noticed by the C# compiler - it's about compile-time constant expressions. So for example:
object x = "mehdi emrani";
string y = "mehdi " + "emrani";
Console.WriteLine(y == x); // True
Here y
is initialized using two string literals which aren't the same as the one used to initialize x
, but the string concatenation is performed by the compiler, which realizes it's the same string it's already used for x
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…