Parse in C#- Parse and TryParse

In C# many times in code, we need to parse string to given data type. Let’s see what is the difference between Parse and TryParse.

Parse will throw and exception when value is no valid and can not be converted to given data type. While TryParse validates and returns true or false (bool) if given input string is valid for conversion to given data type.

Parse and TryParse can be used with different types e.g. int, long, ulong, float, decimal, etc. Let’s understand with Int with example. Same way it works with other said datatypes.

Int.Parse :- It converts given string value to integer. It can be used when you are sure that input string will have valid number value.

Int.TryParse:-  It also converts given string to integer. It can be used when you are not sure that input string will have valid value. It first checked if given string can be parsed to integer and if yes, it converts and fills converted value in out variable.

//When you are sure that input string will have valid values
string stringVal = "32";
int convertedValue = int.Parse(stringVal); // 32     
//when you are not sure that input string could be valid number

        string stringInput = "one12";
        int outputInteger;
        bool isValidValue = int.TryParse(stringInput, out outputInteger);
        if(!isValidValue)
        {
            //Code to handle invalid values
        }

Difference between Convert and Parse:-

Convert handles null values as well; so it will never throw ArgumentNullException even if argument passed is null. On another hand side, if null values are passed to Parse, it will throw an ArgumentNullException.

string inputStr = null;
int outValue= Convert.ToInt32(inputStr); // 0 ; no exception

Similarly, convert handles null arguments in case of other data types too. Here are example of the datatypes which are used with Convert class-

decimal– ToDecimal(String)
float– ToSingle(String)
double– ToDouble(String)
short– ToInt16(String)
int– ToInt32(String)
long– ToInt64(String)
ushort– ToUInt16(String)
uint– ToUInt32(String)
ulong– ToUInt64(String)

Note:- Parse and Convert both will throw exception if any invalid value of string is passed in argument and it is not convertible to given datatype.

So I hope it will help beginners to decide which one to be used where. Precautionary TryParse is recommended as you can handle when invalid values are passed. By it’s ability to handle invalid string, it can also be used to verify if string represents a numeric value. It’s quite small thing but practically useful in many cases.

Happy Learning!

Leave a Reply