Recently, we need to use a string-to-number function to find three similar functions and make a simple comparison.
If the string is not empty, the effect of the three functions is similar.
1 using System;
2 class Hello
3 {
4 static void Main ()
5 {
6 string str = "1234 ";
7 int I = 0;
8 I = Convert. ToInt32 (str );
9 Console. WriteLine (I );
10 Int32.TryParse (str, out I );
11 Console. WriteLine (I );
12 Int32.Parse (str );
13 Console. WriteLine (I );
14}
15}
If the string is null, there is a difference.
1 using System;
2 class Hello
3 {
4 static void Main ()
5 {
6 string str = null;
7 int I = 0;
8 I = Convert. ToInt32 (str); // if no exception is thrown, 0 is returned.
9 Console. WriteLine (I );
10 Int32.TryParse (str, out I); // if no exception is thrown, true or false is returned to indicate whether the resolution is successful. If the resolution is incorrect, the out caller will get a value of 0.
11 Console. WriteLine (I );
12 Int32.Parse (str); // throw an exception
13 Console. WriteLine (I );
14}
15}
It seems that Int32.TryParse () is safer.