Wednesday, July 1, 2009

Differences between Parse, TryParse and ConvertTo [C#]

Parse:

This function takes a string and tries to extract an integer from it and returns the integer.

Followings are the exceptions which occure with parse method

FormatException [ If the string is not a numerical value. ]
OverflowException [ If the extracted number is too big. ]
ArgumentNullException [ If the string value is null. ]

ConvertTo:

This function checks for a null value and if the value is null, it returns 0 instead of throwing an exception.

Followings are the exceptions which occure with ConvertTo method

FormatException [ If the string is not a numerical value. ]
OverflowException [ If the extracted number is too big. ]


TryParse:

This function is new in .Net 2.0. 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, you can avoid the exception and ambiguous result when the string is null. e.g.

float f;
string str = "0.58";
float.TryParse(str, out f);
If string has different separator like comma [ , ] (e.g. 123,45),than we will use TryParse like this
float.TryParse(str,NumberStyles.Any, CultureInfo.InvariantCulture, out f);

No comments:

Post a Comment