• Register
262 points
‚óŹ3

Explanation of problem

In C#, double is a built-in-type what consider as value-type where string is referance-type. Hence by defination all value-type should be non-nullable and have a default value, where all referance-type have a default value of null. So that double have default value of 0 and string have a default value of null. Double value must be numeric, supports floating point numbers and have a approximate range of ±5.0 × 10^−324 to ±1.7 × 10^308 with precision of ~15-17 digits. On the other hand string valule may contain any supported characters in a sequence.

So If we try to convert a string directly by using Convert.ToDouble() method, there is a possibility to generate a runtime format exception that, console input may not contains numeric values and it could not be converted to double-precision floating point number, or a overflow exception that value can be out of the approximate range or digits.

class Program
{
    static void Main()
    {
        //Throws FormatException
        double a = Convert.ToDouble("12rvbv.89");
        //Throws OverflowException
        double b = Convert.ToDouble( "31415926535897932384626433832795028841971693993751058209749445923078164062862089986280.348253421170679" );
        
    }
}

Solution of the problem

Use Double.TryParse() method to perform this convert operation. Provide the targeted string what sould be convert as 1st parameter and a out variable of type double as 2nd parameter which will be accessable in main method. This method returns boolean either true for successful converison and false for failure. If convert operation failed due to exceptions then automatically out variable of TryParse will be 0 as the default value of double type.

class Program
{
    static void Main()
    {
        string str = "3.141592653589793";
        Double.TryParse(str, out double a);
        Console.WriteLine(a);
    }
}