Convert the string to an integer. Whether int. Parse, Convert. ToInt32 or int. TryParse is used ?, Convert. toint32
When we want to Convert a string to an integer int, we may think of the following three methods: int. Parse, Convert. ToInt32 and int. TryParse. Which method is used?
First, consider the possibility of a string. There are roughly three possibilities:
1. null
2. It is not an integer, such as a string.
3. Beyond the Integer Range
Based on the three possibilities of string, try them respectively.
□Use int. Parse
string str = null;
int result;
result = int.Parse(str);
Above, an ArgumentNullException exception is thrown.
string str = "hello";
int result;
result = int.Parse(str);
Above, a FormatException is thrown.
string str = "90909809099090909900900909090909";
int result;
result = int.Parse(str);
Above, an OverflowException exception is thrown.
□Use Convert. ToInt32
static void Main(string[] args)
{
string str = null;
int result;
result = Convert.ToInt32(str);
Console.WriteLine(result);
Console.ReadKey();
}
The value 0 is displayed. If the conversion fails, the default value of int type is displayed. ArgumentNullException is not thrown.
static void Main(string[] args)
{
string str = "hello";
int result;
result = Convert.ToInt32(str);
Console.WriteLine(result);
Console.ReadKey();
}
Above, a FormatException is thrown.
static void Main(string[] args)
{
string str = "90909809099090909900900909090909";
int result;
result = Convert.ToInt32(str);
Console.WriteLine(result);
Console.ReadKey();
}
Above, an OverflowException exception is thrown.
□Use int. TryParse
static void Main(string[] args)
{
string str = null;
int result;
if (int.TryParse(str, out result))
{
Console.WriteLine(result);
}
else
{
Console. WriteLine ("Conversion failed ");
}
Console.ReadKey();
}
Result: The conversion fails.
Conclusion: int is used to capture specific conversion exceptions. parse or Convert. toInt32, and when string is null, Convert. toInt32 does not throw an ArgumentNullException exception. If you only want to check whether the conversion is successful, int is recommended. tryParse. Of course, the preceding values are also suitable for conversion of other value types, such as decimal, decimal. Parse, Convert. ToDecimal, and decimal. TryParse.