1.c# in what case (int) Under what circumstances use Convert.ToInt32?
For example, if you have a string of 3, whether you want to convert it to int (int) 3, or Convert.ToInt32 (3); Or two can be used, why?
Answer: Both are converted to integral types, but they are of different lengths. int is 16 bits, and the bottom one is 32-bit.
First of all, I would like to point out that in C #, int is actually System.Int32, that is, 32-bit.
Second, (int) and Convert.ToInt32 are two different concepts, the former is type conversion, and the latter is content conversion, which is not always equivalent. We know very well that C # provides type checking, you can't cast a string to int, and implicit conversions are 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. Speaking of which, you may ask what is compatible? In fact, the ability to use (int) for strongly typed conversions can only be numeric types, such as long, short, double, and so on, but you need to consider precision when making this transition.
However, we know that the text in the above code actually stores a numeric value, and we want to extract the value and save it as an int for future operations, so you need to convert the content. Content conversion is also called content interpretation, we can change the above code slightly to achieve the purpose:
string text = "1412";
int id = convert.toint32 (text);
In addition, you can 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), and when we use this version to convert a double to an int, ToInt32 checks whether the converted value can be used int indicates whether "out of bounds" will occur, if it is thrown overflowexception, otherwise it will be converted for you, but use (int) for casting, if the number of conversions 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 numeric conversions you make, the precision problem must be considered.