How to use the ToString() method in C#

We can convert a Boolean, an integer, or a character, and so on to a string by using the ToString() method in C#.

Syntax

public override string ToString()

Parameters

This method doesn’t take any arguments.

Return value

This method returns a string as a result.

Code

In the code below, we will create some variables with different data types in C# and convert them to strings using the ToString() method.

// create class
class StringConverter
{
// main method
static void Main()
{
// create variables
int quantity = 20;
double price = 50.00;
char tag = 'T';
bool isFinished = false;
// convert them to strings
string a = quantity.ToString();
string b = price.ToString();
string c = tag.ToString();
string d = isFinished.ToString();
// print out converted values
System.Console.WriteLine(a);
System.Console.WriteLine(b);
System.Console.WriteLine(c);
System.Console.WriteLine(d);
}
}
  • From the code above, all the variables created that are not strings, were all converted to a string by using the ToString() method.

  • In line 14, quantity, which is an integer value, was converted to a string.

  • In line 15, price, which is a double data type, was converted to a string value using ToString().

  • Also in line 16, a character variable tag was converted to a string.

  • And finally, the isFinished variable, a Boolean datatype, was converted to a string using the ToString() method.

Free Resources