Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
c#

How to use the ToString() method in C#

Theodore Kelechukwu Onyejiaku

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);
    }
}
Example of Object Conversion to string using ToString()
  • 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.

RELATED TAGS

communitycreator
c#

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring