What is the purpose of CInt?

keigo

Active member
Joined
Oct 27, 2008
Messages
29
Programming Experience
Beginner
Example:
VB.NET:
CInt(TextBox1.Text)

I have come to learn this CInt but do not exactly know its purpose. Can anyone share?

Thanks.
 
cint converts a string into an integer if possible. Read it as Convertinteger
cint("123") returns an integer 123

cint("Bah, humbug") throws an exception as text can't be converted
 
CInt converts value expression of any given data type into an integer if possible. Have a look through this help page: Type Conversion Functions
When converting string input from user you can not take for granted that conversion from string to integer is possible, and need counter measures for this. As mentioned you can get an exception, which you can use Try-Catch around. Integer.TryParse method can be used and will not throw exception, and it will tell you if conversion was successful. You can also use these methods for validation, for example in Validating event, before doing a direct conversion from other events when you know input data is valid. If you expect only numeric input from user you can also use a control designed for this purpose, like the NumericUpDown control.
 
While it is valid, I never use CInt to convert a value that is not an Integer into an Integer. I use it strictly for casting. For instance, I would never do this:
VB.NET:
Dim str As String = "100"
Dim int As Integer = CInt(str)
because that's converting a value that is a String into and Integer. I would do this though:
VB.NET:
Dim obj As Object = 100
Dim int As Integer = CInt(obj)
because that's casting a value that is already an integer as type Integer. If I want to perform a genuine conversion then I'll use the Convert class or the Parse or TryParse method.

Note that this is my personal preference but I believe it makes code clearer by differentiating conversions and casts. As a developer who codes in C#, where there are no hybrid cast/conversion operators, I find it more consistent.
 
While it is valid, I never use CInt to convert a value that is not an Integer into an Integer. I use it strictly for casting. For instance, I would never do this:
VB.NET:
Dim str As String = "100"
Dim int As Integer = CInt(str)
because that's converting a value that is a String into and Integer. I would do this though:
VB.NET:
Dim obj As Object = 100
Dim int As Integer = CInt(obj)
because that's casting a value that is already an integer as type Integer. If I want to perform a genuine conversion then I'll use the Convert class or the Parse or TryParse method.

But what if the integer that needs to be used comes from user input from a textbox? Then you sort of have to do something like this:

Dim inputFromUser as string = textbox1.text

if isnumeric(inputFromUser) = true
dim integerInput as integer = cint(inputFromUser)
else
msgbox ("Input is not a number")
end if
 
But what if the integer that needs to be used comes from user input from a textbox? Then you sort of have to do something like this:

Dim inputFromUser as string = textbox1.text

if isnumeric(inputFromUser) = true
dim integerInput as integer = cint(inputFromUser)
else
msgbox ("Input is not a number")
end if
Use Integer.TryParse, as in:
VB.NET:
Dim myInt As Integer
If Integer.TryParse(Textbox1.Text.Trim, myInt) = True Then
  'Use your integer variable because it's assigned already
Else
  'Couldn't convert to an integer, alert the user
End If
Another thought, use a NumericUpDown control instead of a TextBox. Set the NUD's Decimal property to 0 (zero) so you'll know that the Decimal to Integer conversion will convert correctly (and without rounding either)
 
Use Integer.TryParse, as in:
VB.NET:
Dim myInt As Integer
If Integer.TryParse(Textbox1.Text.Trim, myInt) = True Then
  'Use your integer variable because it's assigned already
Else
  'Couldn't convert to an integer, alert the user
End If

Any specific reason why your mehtod is better than mine? Seems like it does the same thing (both your code and my code tests if the input value is correct, so no exceptions will happen). Any performance increase?

Another thought, use a NumericUpDown control instead of a TextBox

I have been in situations where a numericupdown is not useful. But you're right, in most situations that control would probably be the best choice
 
Any specific reason why your mehtod is better than mine? Seems like it does the same thing (both your code and my code tests if the input value is correct, so no exceptions will happen). Any performance increase?



I have been in situations where a numericupdown is not useful. But you're right, in most situations that control would probably be the best choice
For one IsNumeric is a legacy function. Also I'm not dimensioning the variable inside the If block (which means the variable isn't available outside of it). The TryParse function is part of the Integer class, which means it's directly tied to the data type that it needs to handle. Also it's doing the numeric checking and converting in one line, instead of two. Plus Integer.TyParse is easier to change code datatypes, because there's a Double.TryParse, Decimal.TryParse, so a simple Find&Replace "Integer" to "Decimal" is a snap.

I've never ran into a situation where a NumericUpDown for numeric input doesn't work, from the end user point of view a NUD is a textbox with convenient up & down buttons (spinners), how can a NUD not ever work?
 
Any specific reason why your mehtod is better than mine? Seems like it does the same thing (both your code and my code tests if the input value is correct, so no exceptions will happen). Any performance increase?



I have been in situations where a numericupdown is not useful. But you're right, in most situations that control would probably be the best choice
IsNumeric cannot distinguish between different types of numbers for a start. Secondly, IsNumeric itself calls Double.TryParse. Thirdly, to determine whether a value is numeric, IsNumeric must parse it, so your code actually parses the same value twice to get a result.
 
Thanks to both of you for the information about the TryParse methods :)

Plus Integer.TyParse is easier to change code datatypes, because there's a Double.TryParse, Decimal.TryParse, so a simple Find&Replace "Integer" to "Decimal" is a snap.

Sorry, I don't buy that one, as it's the same with cint. There's a cint (for integer), cdbl (for double), cdec (for decimal), etc. It's just as easy to do a find&replace with cint than it is with integer.tryparse ;)


I've never ran into a situation where a NumericUpDown for numeric input doesn't work, from the end user point of view a NUD is a textbox with convenient up & down buttons (spinners), how can a NUD not ever work?

Well, in situations where the user also could input text into the same box and NUD wouldn't work. I had a situation where they needed a box where if the value in the box was a number it should call methodA, but if it was text it should call methodB. In that specific situations having one textbox and one NUD at the same time wasn't an option
 
Sorry, I don't buy that one, as it's the same with cint. There's a cint (for integer), cdbl (for double), cdec (for decimal), etc. It's just as easy to do a find&replace with cint than it is with integer.tryparse ;)
You don't have to, but here's a little more about what I was getting at:
VB.NET:
Private Sub DoSomething
  Dim myNumber1, myNumber2, myNumber3 As [B]Integer[/B]
  If [B]Integer[/B].TryParse(Number1TextBox.Text.Trim, myNumber1) = True Then
    'Some code
  End If
  If [B]Integer[/B].TryParse(Number2TextBox.Text.Trim, myNumber2) = True Then
    'Some code
  End If
  If [B]Integer[/B].TryParse(Number3TextBox.Text.Trim, myNumber3) = True Then
    'Some code
  End If
End Sub
A simple Find&Replace the word 'Integer' to 'Decimal' would automatically change all of those and the end result will run flawlessly. If you were to have used CInt then you'd have 2 keywords to change, the word 'Integer' to 'Decimal' and 'CInt' to 'CDec'.
Well, in situations where the user also could input text into the same box and NUD wouldn't work. I had a situation where they needed a box where if the value in the box was a number it should call methodA, but if it was text it should call methodB. In that specific situations having one textbox and one NUD at the same time wasn't an option
Ah, but that means it's not numeric only input anymore. The scenario is numeric only which a NUD handles, if you need characters other than the numbers 0 to 9 and possibly a decimal point then yes you need a textbox because it's not numeric only input.
 
I have been tailing this thread since today 8.00AM. Now, it is 10.26PM. Very informational. Thank you so very much, although I am a bit overwhelmed by the knowledge I have received. This is like a tons of rocks to me.
 
Sorry, I don't buy that one, as it's the same with cint. There's a cint (for integer), cdbl (for double), cdec (for decimal), etc. It's just as easy to do a find&replace with cint than it is with integer.tryparse ;)
When you code .NET you should avoid VB-specific terms intended to make old programmers and legacy code work without too much manipulation. While it would be acceptable to start out with old VB6 code and upgrade it, relying on CInt etc, if you use only methods in common with other .NET syntaxes, it will make it easier for you to:

read a C# example code you find on the web
apply for and do a higher paid C# job because youre' a .NET programmer..

Ends up, avoiding things you find in Microsoft.VisualBasic namespace is probably a commercial decision. The performance gains you'll make are negligible to the extent that if you really cared about that performance, you'd be using somethign way more hardcore (C++) anyway. I think that the biggest bonus is personal pride in being able to "speak" more than one dialect without getting stuck.. You can do that if you avoid "regionalisations" in your dialect. Additionally, in OO paradigm, "ungrouped" functions such as CInt() that don't appear to belong to anything are generally seen as an "old" way of coding.. You now have object.action rather than action(object).. i.ToString() versus CStr(i), where the action is directly influenced by the instance contents of the object. Integer.TryParse is a static action(object), true.. but it's grouped into Integer.<Things> as opposed to Double.<Things> and hence forms a "Factory" pattern. CInt() isnt really a factory pattern because there isnt an identifiable factory.



In that specific situations having one textbox and one NUD at the same time wasn't an option
And the TryParse method would solve it perfectly: if it parsed to a number, do number, if it didnt, do text.
 
Back
Top