System.Object.ReferenceEquals method

K

Kiran A K

hi,
consider the following piece of code:
string s1 = "kiran";

string s3 = s1.Clone() as string;

Console.WriteLine(System.Object.ReferenceEquals(s1, s3));

The above piece of code gave me true while i was expecting false.

s3 is a clone of s1. so s1 and s3 should be separate objects right?

as a result, one would expect "ReferenceEquals" to return false...

can anyone pls explain what exactly is happening?

regards,

kiran
 
S

Stoitcho Goutsev \(100\)

Kiran A K,

I suggest reading some information on string interning. If the string is
interned whenever you try to get a reference to the string it will always
return the same reference.
 
J

Jon Skeet [C# MVP]

Stoitcho said:
I suggest reading some information on string interning. If the string is
interned whenever you try to get a reference to the string it will always
return the same reference.

It's not really anything to do with interning. It's arguable that
String.Clone doesn't properly implement ICloneable.Clone, which states
that a reference to a *new* object is returned. However, as has been
pointed out, the documentation for String.Clone itself explains what's
going on.

Any immutable class could implement the same behaviour though, without
having any concept of interning.

Jon
 
S

Stoitcho Goutsev \(100\)

Jon,

Thanks for the clarification.

Frankly I didn't read the docs on this (I should've). I'd expected this
behavior for interned strings and expected the Clone method to return new
copy for not-interned. However you are right that this implemetation could
make sense to any immutable types, even though the name of the method -
Clone, is little bit confusing in this case.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top