What is the difference between Parse() and TryParse()?
Parse method is used to parse any value to specified data type.
For example
string test = "42";
int32 Result;
Result = Int32.Parse(test);
This will work fine bt what if when you are aware about the value of string variable test.
if test="abc"....
In that case if u try to use above method, .NET will throw an exception as you are trying to convert string data to integer.
TryParse is a good method if the string you are converting to an interger is not always numeric.
if(!Int32.TryParse(test,out iResult))
{
//do something
}
The TryParse method returns a boolean to denote whether the conversion has been successfull or not, and returns the converted value through an out parameter.
**declare variable iResult of Int32.
*Parse throws an exception if it cannot parse the value, whereas TryParse returns a bool indicating whether it succeeded.
*TryParse does not just try/catch internally - the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally the Parse method will call TryParse and then throw an exception if it returns false.
In a nutshell, use Parse if you are sure the value will be valid; otherwise use TryParse.
DOWNLOAD
No comments:
Post a Comment