Compare String and Object in C#

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

See this code:

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

that returns true.

6条回答
  •  难免孤独
    2020-11-30 23:02

    Most probably the references are compared (standard Equals implementation for object). In the first example C# optimizes constant strings, and so y and x actually point to the same object, hence their reference is equal. In the other case, y is created dynamically, and so the reference is different.

提交回复
热议问题