C # in (int), int. Parse (), Int. The difference between TryParse () and Convert.ToInt32 ()

Source: Internet
Author: User

1) for converted objects, Convert.ToInt32 () can be of various types (example out of a numeric type outside bool,datetime, etc.), Int. TryParse () and Int. Parse () can only be an integer string type (that is, the form after various integer tostring (), cannot be a float, or int. Parse () will appear with an incorrect string format for the input int. TryParse () also returns FALSE, the output parameter is 0, and (int) can only be a numeric type (example Float,int,uint, etc.);

2) for null value NULL, from the point of Operation Error, (int) cast and int. Parse () does not accept that null;convert.toint32 () is actually a judgment before the conversion, if the parameter is NULL, return 0 directly, otherwise call Int. Parse () is converted, int. TryParse () is actually a pair of int. Parse () Does an exception handling, returns False if an exception occurs, and returns the output parameter to 0;

3) for floating-point type of trade-offs, floating-point type only Convert.ToInt32 () and (int) can be converted, but it is also a trade-off, Convert.ToInt32 () take the trade-offs are rounding, and (int) is to intercept the integer portion of the floating-point type, Ignoring fractional portions, such as Convert.ToInt32 (1.499d) and (int) 1.499d, returns 1,convert.toint32 (1.5D) and returns 2, while (int) 1.5d returns 1;

4) for overflow, convert large data types to small data types when Convert.ToInt32 () and Int. Parse () will report an overflow error, the value is too large or too small for Int32, and (int) does not error, but the return value is-1.

So, we choose the conversion method before the data conversion is prudent, if the number type can be considered directly with (int) cast, if it is an integer string type, consider using Int. Parse () to convert, if not both, consider converting with Convert.ToInt32 ().

C # in (int), int. Parse (), Int. The difference between TryParse () and Convert.ToInt32 ()

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.