The following is a listing of a program that allows the user to move a label around on the screen by entering the X and Y properties of a point. The label moves when that point is assigned as the Location property of the label.
Dim ptLabelloc As Point Private Sub btnMove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMove.Click ptLabelloc = New Point ptLabelloc.X = CInt(txtX.Text) ptLabelloc.Y = CInt(txtY.Text) lblmoves.Location = ptLabelloc lblmoves.Text = ptLabelloc.ToString() End Sub
The Dim statement at the start of the program creates an object variable called ptLabelloc. Object variables are like the scalar variables we have used previously, but their values are objects rather than single numbers, strings or booleans.
Let's look more carefully at the event handler:
Visualizing memory allocation may clarify the difference between object variables and scalar variables. With scalar variables, we have seen that the compiler sets aside a place in memory to hold one value, perhaps an integer, and gives it a name so it can later be retrieved or changed.
Memory allocation is a little more complex with object variables. In our example, the execution of the Dim statement would have set aside a place in memory and given it the name ptLabelloc. Instead of holding a value, that space holds the address of the properties of the object.
When the computer executes the assignment statement, it constructs the new Point by setting aside memory to hold its property values and putting the address of the block of memory that holds those values in ptLabelloc. Since it has the address of the properties, the computer can find them whenever the program refers to them. Note that it assigned the properties default values of 0.
Programmers would call the address a pointer because it points to the place in memory where the property values are stored.
We will add one more facet to the idea of an object variable in a subsequent note, but for now, this should make it concrete.