Hi,
Does "hello".ToString() produce a new string or is it smart enough to return a reference to the same object?
Hi,
Does "hello".ToString() produce a new string or is it smart enough to return a reference to the same object?
To answer your question in the title: no.
According to .NET Reflector, calling .ToString() or .ToString(IFormatProvider) on a string it just returns itself.
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.