Parse vs. TryParse

Parse TryParse
Parse is used to convert data from string to other data type. It always expects a string to be passed.

Parse throws an exception if it can’t perform conversion successfully.

Ex :

using System;
class parse_ex
{
     static void main()
     {
        string strNumber=”100”;
        int i=int.Parse(strNumber);
        Console.WriteLine(i);
      }
}

Output : 100

Here you can see that the data “100”  which is a string data type has been parsed successfully. Now imagine if the data that was stored was something like below.

string strNumber=”WOTB”;

Now this time, when you run the same program again, it will give you a FORMAT EXCEPTION and the program will stop.

TryParse is an another version of Parse which converts data from string to other data type.

This method is bit different than Parse as it takes two arguments. First parameter is the variable you want to parse and second parameter is the one to which the parsed value will be outputted.

Ex :

using System;
class tryParse_ex
{
    static void main()
    {  string strNumber=”WOTG”;
       int i=0;
       int.TryParse(strNumber , out i);
       Console.WriteLine(i);
    }
}

Output : 0

This program will give output 0 and not 100. It can not parse it since it is alphanumeric. If it would have been, the output would have been 100.

TryParse does not throw an exception if conversion fails but returns Boolean value. It returns false and eliminates FormatException in case of invalid data or failure of parsing.