Search code examples
vb.netarrayswindows-forms-designerfriend

Initialize a friend array in main form, VB



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


Solution

  • 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)