C# String - ToString() Method



The C# String ToString() method converts the value of the current object to a string. It returns the current string object without any formatting, transformation, or other operations on the string.

It is an overridden Method. So, it overrides the Object.ToString method, which is the base method in the System.Object class.

Syntax

Following is the syntax of the C# string ToString() method −

public override string ToString();

Parameters

This method accepts a single parameter −

  • provider: It is an optional parameter that supplies culture-specific formatting information.

Return Value

This method returns the current string.

Example 1: Using Default ToString Method

Following is a basic example of the ToString() method to convert the value of this instance to a string −

using System;
class Program {
   public static void Main() {
      String str1 = "123";
      String str2 = "abc";
      
      Console.WriteLine("Original str1: {0}", str1);
      Console.WriteLine("Original str2: {0}", str2);
      
      str2 = str1.ToString();
      if (str2 == "123") {
         Console.WriteLine("New str2: {0}", str2);
      }
   }
}

Output

Following is the output −

Original str1: 123
Original str2: abc
New str2: 123

Example 2

Let's look at another example. Here, we use the ToString() method to convert the current string to a string −

using System;
class Program {
   static void Main() {
      string original = "Hello, tutorialspoint";
      string result = original.ToString();
      
      Console.WriteLine(result);
   }
}	

Output

Following is the output −

Hello, tutorialspoint

Example 3: ToString Method Integrates with Object

The below example shows how the ToString() method seamlessly integrates with the general behaviour of objects in C# −

using System;
class Program {
   public static void PrintObjectDetails(object obj) {
      Console.WriteLine(obj.ToString());
   }
   public static void Main() {
      string message = "Tutorialspoint!";
      PrintObjectDetails(message);
   }
}

Output

Following is the output −

Tutorialspoint!
csharp_strings.htm
Advertisements