开发者

Does ToString() produce a new string on when used on strings?

Does "hello".ToString() produce a new string or is it smart e开发者_开发技巧nough 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.


It is smart enough (at least in Mono):

public override String ToString ()
{
return this;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜