Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To convert a string to a number in C#, you can use the built-in methods provided by the Convert class:

  1. Use the Convert.ToInt32 method to convert a string to an integer:

    string str = "123";
    int number = Convert.ToInt32(str);
    
  2. Use the Convert.ToDouble method to convert a string to a double:

    string str = "123.45";
    double number = Convert.ToDouble(str);
    
  3. Use the int.TryParse or double.TryParse methods to convert a string to an integer or double, respectively. These methods return a boolean value indicating whether the conversion was successful or not:

    string str = "123";
    int number;
    if (int.TryParse(str, out number))
    {
       // Conversion successful
    }
    
    string str = "123.45";
    double number;
    if (double.TryParse(str, out number))
    {
       // Conversion successful
    }
    

Note that if the string cannot be converted to a number, an exception will be thrown in the first two methods. The TryParse methods are safer since they will not throw an exception and instead return a boolean value indicating the success of the conversion.