开发者

Object.ReferenceEquals returns incorrect results (in Silverlight 3 at least)

I just discovered a very strange behaviour. I have a class with a string property. In the setter of this property I compare the old value with the new value first and only change property if the values differ:

        set
        {
            if ((object.ReferenceEquals(this.Identifier, 开发者_运维问答value) != true))
            {
                this.Identifier = value;
                this.RaisePropertyChanged("Identifier");
            }
        }

But this ReferenceEquals almost always returns false! Even if I call object.ReferenceEquals("test", "test") in Quick Watch I get false.

How is this possible?


That's because strings are immutable in C#:

The contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this.

Since you can't modify an existing string reference, there's no benefit in reusing them. The value passed to your property setter will always be a new string reference, except maybe if you do this.Identifier = this.Identifier;.

I'll try to clarify with an example:

string s = "Hello, ";  // s contains a new string reference.
s += "world!";         // s now contains another string reference.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜