user76071
user76071

Reputation:

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

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

Upvotes: 9

Views: 216

Answers (3)

Steve Guidi
Steve Guidi

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

Thilo
Thilo

Reputation: 262474

It is smart enough (at least in Mono):

public override String ToString ()
{
return this;
}

Upvotes: 0

Daniel A. White
Daniel A. White

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

Related Questions