Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Here's my code that doesn't work, I get thrown lots of exceptions and can't seem to understand why...

 

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?

Posted

You didn't create any new structures, and you didn't size the arrays.

 

' 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

  • Leaders
Posted

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...

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

[sIGPIC]e[/sIGPIC]
Posted
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.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...