Basically, I have been using both Integer.Parse
and CInt in most of my daily programming tasks, but I\'m a little bit confused of what the difference is between
The <Data Type>.Parse
methods are used to extract a value of the type from a string that represents the value (e.g 2 from "2") The C<Data Type>
functions operate on expressions and return a variant sub-typed to the desired type (e.g. CInt("2")
OR CInt(SomeDouble + SomeDouble)
, etc.).
Looking with ILDASM at some sample code you can see that CInt is converted to this call:
Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.Conversions::ToInteger(string)
Using .NET Reflector, you can extract this piece of code:
Public Shared Function ToInteger(ByVal Value As String) As Integer
Dim num As Integer
If (Value Is Nothing) Then
Return 0
End If
Try
Dim num2 As Long
If Utils.IsHexOrOctValue(Value, (num2)) Then
Return CInt(num2)
End If
num = CInt(Math.Round(Conversions.ParseDouble(Value)))
Catch exception As FormatException
Throw New InvalidCastException(Utils.GetResourceString("InvalidCast_FromStringTo", New String() { Strings.Left(Value, &H20), "Integer" }), exception)
End Try
Return num
End Function
You can see that internally it calls Conversions.ParseDouble.
Therefore, as already explained by Binary Worrier, use Integer.Parse for string coercing and CInt only for casting.
Here is a real difference : Integer.parse("1.00") will thrown an error. CInt("1.00") will work
CInt
does a whole lot more than Integer.Parse.
CInt
will first check to see if what it was passed is an integer, and then simply casts it and returns it. If it's a double it will try to convert it without first converting the double to a string.
See this from the help for CInt
and other Type Conversion Functions
Fractional Parts. When you convert a nonintegral value to an integral type, the integer conversion functions (CByte, CInt, CLng, CSByte, CShort, CUInt, CULng, and CUShort) remove the fractional part and round the value to the closest integer.
If the fractional part is exactly 0.5, the integer conversion functions round it to the nearest even integer. For example, 0.5 rounds to 0, and 1.5 and 2.5 both round to 2. This is sometimes called banker's rounding, and its purpose is to compensate for a bias that could accumulate when adding many such numbers together.
So in short, it does much more than convert a string to an integer, e.g. applying specific rounding rules to fractions, short circuting unecessary conversions etc.
If what you're doing is converting a string to an integer, use Integer.Parse (or Integer.TryParse), if you're coercing an unknown value (e.g. a variant
or object
from a database) to an integer, use CInt
.