• Register
262 points
‚óŹ3

Explanation of problem

In C#, System namespace provide Convert class with definations of all possible conversation of data from one type to another. Most commony conversion performs between string to another type. Every type have an standard format so that if value of string formatted correctly only then conversion will be placed, otherwise it will throws the exception called FormatException with default message of "input string was not in a correct format”.

Consider a string value have to convert in double. A string valule may contain any supported characters in a sequence so that, there is a possibility to throw FormatException that, console input may not contains numeric values and it could not be converted to double-precision floating point number.

class Program
{
    static void Main()
    {
        //Throws FormatException
        double a = Convert.ToDouble("111880.vfd45");  
    }
}

Solution of the problem

If you wish to convert a string into a predefined type, then use the your type defination where have a static method TryParse()  to perform this conversation. Provide the targeted string what sould be convert as 1st parameter and a out variable of type you want convert into as 2nd parameter which will be accessable in outer scope of the method. This method returns boolean either true for successful converison and false for failure. If conversion failed due to FormatException then automatically out variable of TryParse will be the default value of your out type.

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