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 classclass StringConverter{// main methodstatic void Main(){// create variablesint quantity = 20;double price = 50.00;char tag = 'T';bool isFinished = false;// convert them to stringsstring a = quantity.ToString();string b = price.ToString();string c = tag.ToString();string d = isFinished.ToString();// print out converted valuesSystem.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 adoubledata type, was converted to a string value usingToString(). -
Also in line 16, a character variable
tagwas converted to a string. -
And finally, the
isFinishedvariable, a Boolean datatype, was converted to a string using theToString()method.