This article provides a more in-depth and detailed analysis of the differences between (int), (), Convert.ToInt32 in c#, which can be used to consolidate learning for beginners. Details are as follows:
1. (int) variable name [Captive type conversion]:
This conversion method is mainly used for numeric type conversion. From int type to long, float, double, decimal type, implicit conversion can be used, but from long type to int type, explicit conversion is required, that is, the data type conversion method, otherwise a compilation error will occur.
This method will unconditionally abandon floating point numbers and lose accuracy.
Of course, this method can also perform object-to-int conversion, but the value of object must be assigned to the value of type int, otherwise a compilation error will occur, and an error will occur when the object is null.
One last thing to avoid,Never use it to process the conversion from char type to int type, otherwise the value passed back is ASCII code., not the value you want.
2. (String type variable name)
This method is to convert the string of numeric content to an int type.If the string content is empty or null, an ArgumentNullException exception is thrown; if the string content is not a number, a FormatException exception is thrown; if the string content represents the number beyond the range that can be represented by the int type, an OverflowException exception is thrown; if the number represented by the string content exceeds the range that can be represented by the int type, an OverflowException exception is thrown;。
One thing you should avoid using this method isOnly string content can be processed, and the string content can only be within the range that can be represented by the int type.
3. (string s, out int result)
This method also converts the string of numeric content to int type, but the advantage of this method is that it will not show exceptions. Return true if the conversion is successful, and false if the conversion fails. Obviously, the last parameter is the output value. If the conversion fails, the output value is 0; if the conversion is successful, the corresponding value is output.
4. Convert.ToInt32
This method can not only convert strings to int type, but also convert values of other types to int type. If a variable is of object or string type, when its value is null, it will be passed back to 0, which will not cause program errors. However, if the value of this string type is, it will still cause program errors when converted to int. This method will round up for floating point numbers.
This method is the same as cast, and cannot be used to deal with char types, otherwise the ASCII code is passed back.