ReferenceEquals working wrong with strings

前端 未结 4 2069
眼角桃花
眼角桃花 2020-12-05 21:03

Why in this situation ReferenceEquals method of object behaves differently?

string a= \"fg\";
string b= \"fg\";
Console.WriteLine(object.Referen         


        
4条回答
  •  悲&欢浪女
    2020-12-05 21:33

    It is behaving correctly in both cases.

    The reason a and b are the same string object is because the compiler has noticed that you specified the same string twice, and has reused the same string object to initialize both a and b.

    This will generally happen with every string constant in your application.

提交回复
热议问题