Confused!!! Can you please help explain?

ATT

New member
Joined
Nov 4, 2007
Messages
2
Programming Experience
Beginner
Much appreciated. Thanks. :confused:

The code below declare a to be an array of size 3 in VB .NET:
Dim a() As Integer = {1, 2, 3}

The size need not be specified because the initialization determines the size. The code below declares b to be an array of size 3 in VB .NET, with no initial values:
Dim b(3) As Integer

The following two lines of code will display the values of b to be the same as a:
b = a
MessageBox.Show(b(0).ToString + " " + b(1).ToString + " " + b(2).ToString)

That is, b was initialized to the same value as a.

In the code above, a(1) is changed after b was set to the array a. You’ll find that b is changed too. Why? How does this differ from integers such as:
Dim x As Integer = 1
Dim y As Integer
y = x
x = 2
MessageBox.Show(y.ToString())
 
The code below declares b to be an array of size 3 in VB .NET, with no initial values:
Dim b(3) As Integer
No, there are 4 elements in that array, index 0 to 3. All elements are initialized to their default value, that is 0 for Integer data type.

The following two lines of code will display the values of b to be the same as a:
b = a

That is, b was initialized to the same value as a.
'b' is here given a new "value", ie it now references the 'a' array object.

In the code above, a(1) is changed after b was set to the array a. You’ll find that b is changed too.
a) No, it wasn't. b) No, it isn't.

How does this differ from integers such as:
Integers are value types, they hold only simple values. Arrays are reference types, they refer to an object instance, several reference type variables can point to the same object.
 
Back
Top