tags:

views:

124

answers:

3

Hi,

Does "hello".ToString() produce a new string or is it smart enough to return a reference to the same object?

+9  A: 

To answer your question in the title: no.

According to .NET Reflector, calling .ToString() or .ToString(IFormatProvider) on a string it just returns itself.

Daniel A. White
Also according to [MSDN](http://msdn.microsoft.com/en-us/library/8tc6ws5s.aspx): "Returns this instance of String; no actual conversion is performed."
NullUserException
@NullUserException - thanks. I didn't know it was actually in the documentation.
Daniel A. White
A: 

It is smart enough (at least in Mono):

public override String ToString ()
{
return this;
}
Thilo
+2  A: 

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.

Steve Guidi