In what case in c# (int), when to use Convert.ToInt32

  
 

What is the case in 1.c# (int) When to use Convert.ToInt32 ?

For example, if there is a string type 3, it is necessary to convert it to int type (int) 3, still use Convert.ToInt32 (3); or both can be used, why?

Answer: Both of these are converted to integers, but they are different in length. Int is 16-bit, and the following is 32-bit

First, I want to point out that in C#, int is actually System.Int32, which is 32-bit.

Secondly, (int) and Convert.ToInt32 are two different concepts, the former being type conversions and the latter being content conversions, which are not always equivalent. We know that C# provides type checking. You can't cast a string to an int. Implicit conversion is even more impossible. For example, the following code won't work:

string text = "1412"; int id = (int)text;

Because string and int are two completely different and incompatible types. Having said that, what might you ask is compatible? In fact, you can use (int) for strong type conversion only for numeric types, such as long, short, double, etc., but you need to consider the precision problem when doing this conversion.

However, we are very clear that the text in the above code actually stores a value. We want to extract this value and store it in the form of int for later operation, then you need to do the content. Converted. Content conversion is also called content interpretation. We can achieve the purpose by slightly modifying the above code:

string text = "1412"; int id = Convert.ToInt32(text);

In addition to this, you can also use Int32.Parse and Int32.TryParse to explain.

In addition, you find that Convert.ToInt32 has many overloaded versions, such as Convert.ToInt32(double value);, when we use this version to convert a double to an int, ToInt32 will check the converted value. Whether it can be represented by int, that is, whether or not "out of bounds" will occur, if it will throw OverflowException, otherwise it will be converted for you, but use (int) to cast, if the converted value is greater than Int32.MaxValue, Then you will get a wrong result, such as the following code:

double d = Int32.MaxValue + 0.1412; int i = (int)d;

But no matter what value conversion you make The accuracy problem must be considered.

Copyright © Windows knowledge All Rights Reserved