Reputation:
Does "hello".ToString()
produce a new string or is it smart enough to return a reference to the same object?
Upvotes: 9
Views: 216
Reputation: 20200
You can test this hypothesis with a simple assertion:
using System.Diagnostics;
void ToStringHypothesis()
{
string myString = "Hello!";
string otherString = myString.ToString();
Debug.Assert(Object.ReferenceEquals(myString, otherString));
}
Since strings are immutable in .NET, the sensical implementation of String.ToString()
implementation is to return a reference to itself.
Upvotes: 2
Reputation: 262474
It is smart enough (at least in Mono):
public override String ToString ()
{
return this;
}
Upvotes: 0
Reputation: 190907
To answer your question in the title: no.
According to .NET Reflector, calling .ToString()
or .ToString(IFormatProvider)
on a string
it just returns itself.
Upvotes: 11