Differences between Convert. ToInt32 and Int32.Parse and Int32.TryParse

Source: Internet
Author: User

Using System;
Using System. Collections. Generic;
Using System. Text;
Namespace ConsoleApplication1
{
Class Program
{
Static void Main (string [] args)
{
String myString = "1234 ";
Int myint = 0;
Myint = Convert. ToInt32 (myString );
Console. Write (myint + "\ r \ n ");
Myint = Int32.Parse (myString );

Console. Write (myint + "\ r \ n ");
Int32.TryParse (myString, out myint );

Console. Write (myint + "\ r \ n ");
}
}
}
On the surface, it can be seen that the three methods have achieved the same effect!
Let's change the code:


// String myString = "1234 ";
String myString = null;
Int myint = 0;
Myint = Convert. ToInt32 (myString );
Console. Write (myint + "\ r \ n ");
Myint = Int32.Parse (myString );
Console. Write (myint + "\ r \ n ");
Int32.TryParse (myString, out myint );
Console. Write (myint + "\ r \ n ");

Running result:
If Convert. ToInt32 () is null, 0 is returned instead of an exception;
Int32.Parse () should throw an exception;
If Int32.TryParse () does not throw an exception, true or false is returned to indicate whether the resolution is successful. If a parsing error occurs, the caller will get a value of 0.

Conclusion:
There are almost no differences between the three methods!

If you want to pursue perfection, consider the performance differences:
Int32.TryParse () is better than Int32.Parse () than Convert. ToInt32 ().

Personal suggestion: Use Int32.Parse () in. NET1.1; Use Int32.TryParse () in. NET2.0 ().

Why?
Because: Convert. toInt32 will delegate the final parsing work to Int32.Parse, while Int32.Parse and Int32.TryParse respectively proxy the parsing work directly to Number. parseInt32 and Number. tryParseInt32: the former throws an exception when a parsing error occurs, while the latter returns only false.

Related Article

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.