Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

See this code:

object x = "mehdi emrani";
string y = "mehdi emrani";
Console.WriteLine(y == x);

that returns true.

But this code:

object x = "mehdi emrani";
string y = "mehdi ";
y += "emrani";
Console.WriteLine(y == x);

returns false.

So when I compare String and Object in first code I get true.
But when I compare them in second code I get false.

Both strings are same but why when I append to the string, my result returns false?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
331 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...