Using Reflector to look at the implementation of String.Clone()
reveals this:
public object Clone()
{
return this;
}
So the answer is "No, there is no difference between assigning and cloning for a string".
However, Copy()
is somewhat different:
public static unsafe string Copy(string str)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
int length = str.Length;
string str2 = FastAllocateString(length);
fixed (char* chRef = &str2.m_firstChar)
{
fixed (char* chRef2 = &str.m_firstChar)
{
wstrcpy(chRef, chRef2, length);
}
}
return str2;
}
This is actually making a copy - but since strings are immutable, it's not very useful anyway.
But - and this is important - Copy()
will return a DIFFERENT REFERENCE from the original string, and Clone()
will return the SAME REFERENCE as the original string.
Another thing to be aware of is string interning which causes strings with identical values to share the data (and therefore have the same string reference).
For example, the following code will print "Same!":
string s1 = "Hello";
string s2 = "Hello";
if (ReferenceEquals(s1, s2))
Console.WriteLine("Same!");
But the following code will print "Not same!", even though the string values are the same:
string s1 = "Hello";
string s2 = "He";
string s3 = "llo";
string s4 = s2 + s3;
if (!ReferenceEquals(s1, s4))
Console.WriteLine("Not Same!");
We can explicitly intern s4
, so that the following prints "Same!":
string s1 = "Hello";
string s2 = "He";
string s3 = "llo";
string s4 = s2 + s3;
s4 = string.Intern(s4);
if (ReferenceEquals(s1, s4))
Console.WriteLine("Same!");