Array of objects

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,
I need to create an Array with objects of another class. I thought I could
make it the follwing way.. but it is not working.. anyone who know how to
make it work?
Class1
Private xCollection() As Class2
for i = 0 to 10
xCollection(i) = new Class2(5)
next


Class2
Private i As integer
Public Sub New(byVal instX As integer)
i= instX
End Sub
 
Lamis said:
Hi,
I need to create an Array with objects of another class. I thought I could
make it the follwing way.. but it is not working.. anyone who know how to
make it work?
Class1
Private xCollection() As Class2
for i = 0 to 10
xCollection(i) = new Class2(5)
next


Class2
Private i As integer
Public Sub New(byVal instX As integer)
i= instX
End Sub
--

Hi,

I would use a list instead (like the other poster suggested) you can even
use a generic list: (only in .net 2.0)

Imports System.Collections.Generic Class1
Private xCollection As New List(Of Class2)
for i = 0 to 10
xCollection.add(new Class2(5))
next


Class2
Private i As integer
Public Sub New(byVal instX As integer)
i= instX
End Sub

then you can access the properties and methods of class2 directly from the
List.

say that Class2 also has a property called Name then you can do this:

xCollection(2).Name = "A Name"

Where the '2' stands for the index of the List.



Best Regards,

Jeroen Vandezande

ps: I hope the VB.net code is correct, I normally code in Chrome so my
excuses for this.
 
See other posts for alternatives...

As for why it doesn't work please always include the exact error message you
have instead of just saying "it doesn't work". For now it looks like to me
you forgot to indicate how much elements your array should hold.

Patrice
 
Patric, u are absolutly right... I will include the error message next time..
the problem was that I didn't indicate how much elements it should holds...
the problem is now solved..

thanks to cor and jeroen
 
Back
Top