C# String ToString

String type

A string can be converted into a string. The C# programming language provides the ToString method on all type instances, including the string type. And with it we convert strings into strings.

This C# example program uses the ToString method on string. It converts strings to strings.

Example

Note

First, as we begin, we should note that this program prints my name four times. If you decide to execute it on your computer, feel free to change the name to your own name. The first Console.WriteLine call shows that the value.ToString() method returns a string type; its content is the same as the original value.

Program that calls ToString() [C#]

using System;

class Program
{
    static void Main()
    {
	string value = "sam";
	Console.WriteLine(value.ToString());
	Console.WriteLine(value.ToString().ToString());
	Console.WriteLine(value.ToString().ToString().ToString());
	Console.WriteLine(value.ToString().ToString().ToString().ToString());
    }
}

Output

sam
sam
sam
sam
Note

ToString(). As revealed above, the first ToString call returns the original string reference. The virtual execution engine does this by pushing the instance reference onto the evaluation stack and then executes a return instruction.

ToString().ToString(). The second ToString() call, chained upon the first ToString() call, also returns the string reference. It is interesting that the ToString method works the same way when called twice in a row.

ToString().ToString().ToString().ToString(). This is where the analysis becomes really interesting. After the first, second, third, and fourth ToString calls execute, the same string reference is returned each time.

Summary

The C# programming language

The string ToString method returns the original string reference; in other words, it enables you to convert a string instance into that same string instance. This article is limited in scope: it established that calling ToString one, two, three and four times in a row will continue returning the same string. But we have not shown whether calling ToString a fifth time or further times will continue this pattern.

String Type
.NET