Fill an array dymanically

  • Thread starter Thread starter Raterus
  • Start date Start date
R

Raterus

I know this may seem like a silly question, but I can't figure it out!

I've made my own object, which has five properties. When I instantiate this object, the new constructor is passed these values. I need to create a dynamic array of these objects, and I don't know how many could be created.

Basically I want to do this (which doesn't work..) "TemplateSearch" is my object

....
Private search() As TemplateSearch
Private searchCount As Integer = 0

For each blah in myBlahs
search(searchCount) = new TemplateSearch(f1, f2, f3, f4, f5)
searchCount = searchCount + 1
Next
....

I get the dreadful "Object reference not set to an instance of an object.",

I know I can put a number when I declare my object, "Private search(100) as TemplateSearch", but that seems like a cop-out, and if I ever insert more than this number, it'll break. Can someone help me out on this?

Thanks!
--Michael
 
Raterus said:
I know this may seem like a silly question, but I can't figure it out!

I've made my own object, which has five properties. When I instantiate this object, the new constructor is passed these values. I need to create a dynamic array of these objects, and I don't know how many could be created.

Basically I want to do this (which doesn't work..) "TemplateSearch" is my object

...
Private search() As TemplateSearch
Private searchCount As Integer = 0

For each blah in myBlahs
search(searchCount) = new TemplateSearch(f1, f2, f3, f4, f5)
searchCount = searchCount + 1
Next
...

Ever thought about dimensioning your array before using it?

\\\
ReDim search(whatevernumberyouneed)

For each blah in myBlahs
search(searchCount) = new TemplateSearch(f1, f2, f3, f4, f5)
searchCount = searchCount + 1
Next
///
 
* "Raterus said:
I've made my own object, which has five properties. When I instantiate this object, the new constructor is passed these values. I need to create a dynamic array of these objects, and I don't know how many could be created.

Basically I want to do this (which doesn't work..) "TemplateSearch" is my object

...
Private search() As TemplateSearch
Private searchCount As Integer = 0

For each blah in myBlahs
search(searchCount) = new TemplateSearch(f1, f2, f3, f4, f5)
searchCount = searchCount + 1
Next
...

Have a look in the documentation for 'ReDim Preserve'. You can use it
to change the size of the array. Notice that this may dramatically
reduce the performance if you increase the size of the array in every
iteration of the loop. Instead, you can create an array with maximum
size (maybe you have to determine an upper bound using a heuristic),
assign the object to the element the counter is pointing to, and after
assigning all objects, perform a 'ReDim Preserve' with the number of
items in the array - 1.

Alternatively, you can use a more dynamic data structure to store your
items, like an 'ArrayList', or a 'Collection'.
 
Back
Top