Sunday, December 19, 2010

Convert Vs Parse Vs TryParse

What’s the difference between all three:

Covert:
Contains a series of functions to convert one base class into another. It just checks for a null string (if the string is null it returns zero unlike the Parse) then just calls Int32.Parse(string).

Parse:
This function will take a string and attempt to extract an integer out of it and then return the integer. If it runs into something that it can’t parse due to incorrect or null value then it throws a FormatException or if the number is too large an OverflowException.

TryParse:
If TryParse is unable to parse the string it does not throw an exception like Parse does. Instead, it returns a Boolean indicating if it was able to successfully parse a number.

In general it’s a best practice to use TryParse and do precondition checks before using the output value. Simply because:
1.       Return Boolean value: No exceptions which could slow down performance. Instead Boolean return value which gives indication if the value  is successfully converted or not.
2.       Precondition check: Before using the actual value you are sure it’s actually converted