Data type conversion

I tried to write a program to add two numbers. But, as you see, it has a logical error. It executes, but does not do what I had wanted it to do. I had to debug the program.

I had named the user interface controls:

And the btnAdd_Click event handler was:

Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
  lblSum.Text = txtFirstNumber.Text + txtSecondNumber.Text
End Sub

The problem is that txtFirstNumber.Text + txtSecondNumber.Text is a string expression, so the numbers the user entered were treated as strings and concatenated instead of being added. (VB treats the + operator as a synonym for &).

I needed a way to convert the data types of the inputs from string to numeric. VB.NET has a number of intrinsic (built-in) functions for converting data from one type to another. One of those is the CInt function which converts string data to numeric data. I modified the event handler to convert the string input to numeric data as follows:

Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
  lblSum.Text = CInt(txtFirstNumber.Text) + CInt(txtSecondNumber.Text)
End Sub
That seemed reasonable, but it introduced a syntax error. I now had a numeric expression on the right hand side of the assignment statement and the Text property on the left hand side is a string.

To fix that error, I used the CStr function to convert the type of the result to a string before assigning it to lblSum.Text.

Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
  lblSum.Text = CStr(CInt(txtFirstNumber.Text) + CInt(txtSecondNumber.Text))
End Sub
The addition program worked after that change was made.

We have seen two VB.NET functions for data type conversion:

CInt(<string expression>)
and
CStr(<numeric expression>)

VB has several functions for data type conversion, including the following:

Type Conversion function
Byte CByte
Short CShort
Integer CInt
Long CLng
Single precision CSng
Double precision CDbl
String CStr

Note that even with Option Strict On, some automatic type conversions are allowed. For example, if you write:

   Dim A as single
   Dim B as double
   A = B
   B = A
A = B has a syntax error because you are trying to convert a double precision number to single precision. Like putting a big foot in a small shoe.

B = A is OK because no information is lost when you convert a single precision number to double precision. A small foot has plenty of room in a big shoe -- no information is lost.


Disclaimer: The views and opinions expressed on unofficial pages of California State University, Dominguez Hills faculty, staff or students are strictly those of the page authors. The content of these pages has not been reviewed or approved by California State University, Dominguez Hills.