In this article, we will check whats the main differences between the int.Parse and int.TryParse. Both int.Parse and int.TryParse is used to convert the string to an int value.
Use:
int.Parse: Converts the string representation of a number to its 32-bit signed integer equivalent.
int.TryParse: Converts the string representation of a number to its 32-bit signed integer equivalent.
A return value indicates whether the conversion succeeded.
Example:
string valS = "90";
int valI = int.Parse(valS);
In the above example value is getting converted to 90
string valS = "90";
int value;
bool isConverted = int.TryParse(valS, out value);
The above code is returning the output as true
int.Parse throws the exception in the different scenarios, will discuss in the below points
- Not handled the null value, throws the exception System.ArgumentNullException
2. Not handled the format of the string throws the System.FormatException
3. int.Parse not handle the out of ranges integers, throws the System.OverflowException exception
But int.TryParse does not throw any exception in any condition but return the isConverted false and value 0 Refer to the below
When we are not sure about the data of string, that condition we can use int.TryParse else you can go for the int.Parse, again its totally depends on the context.
Need help?
Read this post again, if you have any confusion or else add your questions in Community