Compare String and Object in C#

后端 未结 6 586
感情败类
感情败类 2020-11-30 22:30

See this code:

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

that returns true.

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 23:05

    In the first case, .NET performs string constant optimization and allocates only one String instance. Both x and y points to same object (both the references are equal).

    But in the second case x and y are pointing to different String instances. Adding "ermani" to y creates a third string object.

    "==" operator basically returns true if operands on both sides refer to same object. In the first case x and y refer to same object and in the seconds case x & y refer different objects.

提交回复
热议问题