What is the difference between Type Conversion methods Int.TryParse() Vs Int.Parse() Vs Convert.ToInt() method in C# ?
Traditionally, we use int.Parse() or Convert.ToInt() method to convert a string to a integer value. With the introduction of .NetFramework 2.0, we have one more method for type conversion called TryParse() method with performance improvements. This method will take the string to be converted as first argument and an out parameter of type int as a second argument and return a Boolean value indicating success or failure.
Syntax
Int.TryParse(String,out Int)
bool.TryParse(String,out bool)
Usage
string strAge = "25";
int Age = 0;
if (!int.TryParse(strAge, out Age))
{
//Assign a default value
Age = 18;
}
When we use int.Parse() method, it will throw an exception for failure which should be catched for assigning a default value. Convert.ToInt() will return a 0 when NULL is passed, else it will again call int.Parse() method for conversion.
Hence, it is best to use TryParse() method for type parsing which is optimised for good performance!
Refer the following post for performance calculations for all the 3 methods.
|