Comparison of Int32.Parse (), Int32.TryParse () and Convert. ToInt32 ()

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.