How to successfully create a Structure Array?

Nazgulled

Centurion
Joined
Jun 1, 2004
Messages
119
Here's my code that doesn't work, I get thrown lots of exceptions and can't seem to understand why...

Visual Basic:
Friend Structure structTest
    Dim varA As String
    Dim varB As Integer
    Dim varC() As String
End Structure
 
Friend struct() As structTest
 
struct(0).varA = "blabla"
struct(0).varB = 10
struct(0).varC(0) = "aaa"
struct(0).varC(1) = "bbb"
struct(0).varC(2) = "ccc"

A first chance exception of type 'System.NullReferenceException' occurred in Network Switcher.exe
Object reference not set to an instance of an object.
This is what happens at line: struct(0).varA = "blabla"

How can I fix this?
 
You didn't create any new structures, and you didn't size the arrays.

Visual Basic:
' size the array to hold 10 items:
struct = New structTest(9) {}
' add ten items
For i As Integer = 0 To 9
   ' Create a new struct
   struct(i) = New structTest
   ' assign some values
   struct(i).varA = "struct" & i.ToString
   struct(i).varB = i
   ' create a new array and put in one short string: item A, B, C etc...
   struct(i).varC = New String() {"item" & Chr(Asc("A"c) + i)}
Next
 
Hum... Thanks, I always had troubles with initializing arrays in VB...

But, do I really have to size the array? What if I don't know it's size?
 
You don't need to create the structures. They are created simply by being declared, unlike classes. They aren't initialized, though, unless you call a constructor or an initialization method...
Visual Basic:
Dim X As SomeStruct 'Not initialized
Dim X As New SomeStruct(5, "Doodie") 'Initialized
 
Dim Y As SomeStruct
Y.Initialize("Ketchup") 'Initialized.
You should probably create a constructor (Sub New).

As far as sizing arrays, you MUST create an array. If you don't, well, then, believe it or not, it doesn't exists.

So, what if you don't know the size? Then, most likely, you shouldn't be using arrays. Try using an ArrayList or a HashTable or a generic List(of T) class, or a Dictionary(Of Integer, String).
 
I didn't quite understood your post... I talk about create structures, declaring, initalizing and constructors but I can't relate that to a structure array and how correctly use it for what I'm attempting to do as described in the first post.
 
Back
Top