C# Tutorial C# Advanced C# Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

C# - String ToString() Method



The C# string ToString() method is used to convert the value of the instance to a string. It returns the instance of the string and no actual conversion is performed.

Note: This method can be overloaded by passing different type of arguments to it.

Syntax

public override string ToString();  
public string ToString(IFormatProvider provider);

Parameters

provider Specify an object that supplies culture-specific formatting information.

Return Value

Returns the instance of string.

Exception

NA.

Example:

In the example below, ToString() method is used to convert the value of MyInt to a string.

using System;

class MyProgram {
  static void Main(string[] args) {
    int MyInt = 12345;
    string MyStr = MyInt.ToString();

    Console.WriteLine(MyStr);  
  }
}

The output of the above code will be:

12345

Example:

In the example below, ToString() method is used to convert the value of date to a string, using different cultures.

using System;
using System.Globalization;

class MyProgram {
  static void Main(string[] args) {
    DateTime date = new DateTime(2019, 10, 10, 16, 37, 0);

    string MyStr1 = date.ToString(new CultureInfo("en-US"));
    string MyStr2 = date.ToString(new CultureInfo("fr-FR"));
    string MyStr3 = date.ToString(new CultureInfo("de-DE"));

    Console.WriteLine(MyStr1);
    Console.WriteLine(MyStr2);
    Console.WriteLine(MyStr3);  
  }
}

The output of the above code will be:

10/10/2019 4:37:00 PM
10/10/2019 16:37:00
10.10.2019 16:37:00

❮ C# String Methods

5