Structures and ArrayLists

Audax321

Regular
Joined
May 4, 2002
Messages
90
Hello,

I'm declaring a structure (that will include other variable types in the future) as follows:

Code:
Structure SearchResults
     Dim FileNames As ArrayList
     Dim Paths As ArrayList
End Structure

But, I'm getting the following error:

Code:
An unhandled exception of type 'System.NullReferenceException' occurred in WindowsApplication1.exe

Additional information: Object reference not set to an instance of an object.

I tried changing the structure declaration to include ...as New ArrayList, but thats not allowed...

Thanks for any help :)
 
It's best to put reference types inside classes, not a structure. Structures work a bit differently and you can't set default values from outside of properties or methods like you can in classes.

Change your structure to a class, and change your ArrayList declarations to this;

Dime xxx As New ArrayList()
 
I kind of understand what your saying, but I don't have much experience (read: no experience :) ) using classes. How would I access the two variables afterwards?

The way I wanted to use the structure was to declare variables of the structure's type and then use the variables to return various items from a function.

for example:

Code:
Structure SearchResults
     Dim FileNames As ArrayList
     Dim Paths As ArrayList
End Structure

Private Function DoStuff() as SearchResults
    Dim Results as SearchResults

    '''''do the stuff this function does

    Return SearchResults
End Function

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
     Dim Returned as SearchResults

     Returned = DoStuff()

     ''''do some more stuff
End Sub

I'm going to go look up some stuff on classes, I'm pretty new to .NET and used VB6 for not very long.... Thanks .. :)
 
If you want to use properties, like this:
Visual Basic:
Public Class SearchResults
  'these are the private fields
  Private _fileNames As New ArrayList()
  Private _paths As New ArrayList()

  'these are the public properties
  Public Property Paths As ArrayList
    Get
      Return _paths
    End Get
    Set (value As ArrayList)
      _paths = value
    End Set
  End Property    

  Public Property FileNames As ArrayList
    Get
      Return _fileNames
    End Get
    Set (value As ArrayList)
      _fileNames = value
    End Set
  End Property
End Class
To use it,
Visual Basic:
Dim results As New SearchResults()

'do stuff

Return results
It may even be wise to put the "stuff" inside the class so that it can fill itself out. Makes for better OOP code.
 
Thank you very much, VolteFace and wyrd, that worked perfectly... :)

Also, I'm going to buy a book on VB.NET, any recommendations?

I don't need to learn the basics like what a string variable is and stuff, just other syntax such as dealing with classes, owner-drawing, etc....
 
Back
Top