Reputation:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string word = "Shazam!";
Console.WriteLine(word.ToString().ToString().ToString().ToString());
Console.ReadKey();
}
}
}
Can anyone tell me why I can call ToString() like that many times over? Just curious, thanks!
Upvotes: 2
Views: 357
Reputation: 4127
a function chain is occurring here while calling ToString()
becauseToString()
returns a string object
Upvotes: 0
Reputation: 43
The ToString()
method returns a string representing an object.
If you call the ToString()
method of a string, it returns a string - with the same content as it self. If you do it multiple times you get an other string object basically referring to the very same string.
Upvotes: 0
Reputation: 24160
When you apply toSting on an object it returns an object type string. But it again an object and you can apply toString method on it. So your cycle it go infinite. As every new thing will be an object.
Upvotes: 1
Reputation: 11677
ToString() just returns a string representation as a String object. http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx
So word.ToString() returns a String object representing word. The String object has a ToString() function which returns a String object representing the String object... so on.
Upvotes: 0
Reputation: 4019
Well, the ToString()
method returns a System.String
, and System.String
also has a ToString()
method, so you are calling ToString()
on the object returned from the previous ToString()
.
Upvotes: 0
Reputation: 34185
.ToString()
returns a string object. It also implements a .ToString()
which basically returns this
.
Upvotes: 1
Reputation: 1502236
Because string
itself has a ToString()
method (all objects do).
You're calling ToString()
first on word
, then on the result of that call, then on the result of that call etc. Basically each subsequent call acts on the result of the previous one.
It's not limited to ToString()
of course. For example:
int x = new object().ToString().Substring(0, 2).Length;
That calls ToString()
on a new object, then Substring
on the string that's been returned, then Length
on that substring.
Upvotes: 6