Latebound Exception?

  • Thread starter Thread starter VB_Noob
  • Start date Start date
V

VB_Noob

The following code generates a latebound exception.
Anyone have any idea why & how to fix it?

-----------------------------------------------------

Public Class Form1
Structure sTest
Dim ItemA As String
Dim ItemB As String
End Structure

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim aTest As New ArrayList
aTest.Add(New sTest)
aTest(0).ItemA = "test" '<-- LateBound Exception
End Sub
End Class
 
VB_Noob said:
The following code generates a latebound exception.
Anyone have any idea why & how to fix it?

-----------------------------------------------------

Public Class Form1
Structure sTest
Dim ItemA As String
Dim ItemB As String
End Structure

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim aTest As New ArrayList
aTest.Add(New sTest)
aTest(0).ItemA = "test" '<-- LateBound Exception
End Sub
End Class

Is there a reason why you use late binding? If not, enable Option Strict. In
the project's properties and in the IDE options (-> "VB defaults"). Then
you'd come across the problem earlier.

The reason for the exception is that

aTest(0)

returns the item in the ArrayList. As the item is a structure, it is a value
type, and therefore the returned item is a copy of the item in the
Arraylist. If
you'd change the property of the copy, it wouldn't make sense because it
doesn'
change the object in the Arraylist. You'd have to write:

dim tmp as sTest

tmp = directcast(aTest(0), sTest)
tmp.ItemA="test"
aTest(0) = tmp


You can solve it by declaring sTest as a Class. Starting with VB 2005, I
recommend making use of a List(Of sTest) instead of an Arraylist.


Armin
 
Armin Zingler said:
Is there a reason why you use late binding? If not, enable Option Strict.
In the project's properties and in the IDE options (-> "VB defaults").
Then you'd come across the problem earlier.

The reason for the exception is that

aTest(0)

returns the item in the ArrayList. As the item is a structure, it is a
value
type, and therefore the returned item is a copy of the item in the
Arraylist. If
you'd change the property of the copy, it wouldn't make sense because it
doesn'
change the object in the Arraylist. You'd have to write:

dim tmp as sTest

tmp = directcast(aTest(0), sTest)
tmp.ItemA="test"
aTest(0) = tmp


You can solve it by declaring sTest as a Class. Starting with VB 2005, I
recommend making use of a List(Of sTest) instead of an Arraylist.


Armin

Thanks Armin!

After reading your reply, I took out the ArrayList, replacing it with
List(of <Class>) and it worked perfectly. I ofcourse needed to setup
properties & added some routines/functions to do extra stuff but the results
where good :o)
 
Back
Top