Wednesday, March 24, 2010

Convert, Parse and TryParse Methods - Comparing String to Number Conversion Methods

.Net provides several different ways to extract integers from strings. In this article, I will present the differences between Parse, TryParse and ConvertTo.

Parse: This function takes a string and tries to extract an integer from it and returns the integer. If the string is not a numerical value, the method throws FormatException. If the extracted number is too big, it throws OverflowException. Finally, if the string value is null, it throws ArgumentNullException.

Int32 intValue = Int32.Parse(str);

Convert: This function checks for a null value and if the value is null, it returns 0 instead of throwing an exception. If the string is not a numerical value, the method throws FormatException. If the extracted number is too big, it throws OverflowException.

Int32 intValue = Convert.ToInt32(str);

TryParse: This function is new in .Net 2.0. Since exception handling is very slow, TryParse function returns a boolean indicating if it was able to successfully parse a number instead of throwing an exception. Therefore, you have to pass into TryParse both the string to be parsed and an out parameter to fill in. Using the TryParse static method, you can avoid the exception and ambiguous result when the string is null.

bool isParsed = Int32.TryParse(str, out intValue);

Examples:

string str1 = "1234";
string str2 = "1234.65";
string str3 = null;

string str4 = "999999999999999999999999999999999999999999";
int intValue;
bool isParsed;

intValue= Int32.Parse(str1); //1234
intValue= Int32.Parse(str2); //throws FormatException
intValue= Int32.Parse(str3); //throws ArgumentNullException
intValue= Int32.Parse(str4); //throws OverflowException

intValue= Convert.ToInt32(str1); //1234
intValue= Convert.ToInt32(str2); //throws FormatException
intValue= Convert.ToInt32(str3); //0
intValue= Convert.ToInt32(str4); //throws OverflowException

isParsed= Int32.TryParse(str1, out intValue); //isParsed=true 1234
isParsed= Int32.TryParse(str2, out intValue); //isParsed=false 0
isParsed= Int32.TryParse(str3, out intValue); //isParsed=false 0
isParsed= Int32.TryParse(str4, out intValue); //isParsed=false 0

No comments:

Post a Comment