0


I am working on a VB Windows Form and I have a question here about initialize an array (friend variable)

I have a BookInfo class as following:

Public Class BookInfoForm
  Friend _books() As BookInfo
  ...
EndClass

And in my main form, I want to initialize this _books array to be size 4.

What I have tried was:

_bookInfoForm._books(4) = New BookInfo

But this didn't work and it thrown an exception says


Object reference not set to an instance of an object.

I am wondering how I can have the array initialized to size 4. Anyone can help me with this?

Thank you

MPelletier
  • 16,256
  • 15
  • 86
  • 137
Allan Jiang
  • 11,063
  • 27
  • 104
  • 165

1 Answers1

1

First of all you need to initialize your BookInfoForm class, then use Redim to resize your array

Dim BookInfo As New BookInfoForm
Redim BookInfo._books(4)

The Redim could resize your array but also clear all data in the array, if you want to keep those data while resizing your array, then you need to use Preserve after Redim

Redim Preserve BookInfo._books(4)
Nick
  • 1,128
  • 7
  • 12
  • The argument to ReDim is the last index, not the size. "Redim BookInfo._books(4)" will make the array 5 elements long, not 4. From MSDN, [ReDim Statement](http://msdn.microsoft.com/en-us/library/w8k3cys2%28v=vs.80%29.aspx): "The upper bound is the highest possible value for that subscript, not the length of the dimension (which is the upper bound plus one)." – Peter Mortensen Sep 04 '12 at 07:41