We can convert a Boolean, an integer, or a character, and so on to a string by using the ToString()
method in C#.
public override string ToString()
This method doesn’t take any arguments.
This method returns a string
as a result.
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 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.