Question

I'm working in an old web application (vb.net 2003) and I'm trying to use a generic list of a custom class.

I realized that System.Collections.Generic was introduced in .Net 2 according to link

Is there any alternative to the list? For instance an array of class?

Let's say I have the following class definition:

Public Class Box
  Public x As Integer
  Public y As Integer
End Class

And an array of Class Box:

Dim BoxList() As Box
BoxList(0).x = 1
BoxList(0).y = 1

BoxList(1).x = 2
BoxList(2).y = 2

But I'm getting an error when BoxList(0).x = 1 error: Object reference not set to an instance of an object

I'm just guessing here.

Was it helpful?

Solution

Use ArrayList, like this:

Dim BoxList As New ArrayList
Dim box = New Box()
box.x = 1
box.y = 2
BoxList.Add(box)

Note: It is recommended that you add a constructor to the Box class that will accept the x and y values, like this:

Public Class Box
    Public x As Integer
    Public y As Integer

    Public Sub New(ByVal _x As Integer, ByVal _y As Integer)
        x = _x
        y = _y
    End Sub
End Class

Now you can shorten your ArrayList code to this:

Dim BoxList As New ArrayList
BoxList.Add(New Box(1, 2))

To use the values in the ArrayList you will need to un-box (pun not intended) the value out of the ArrayList, like this:

For Each box In BoxList
    ' Use x value, like this
    CType(box, Box).x
Next

OR (as Meta-Knight suggested)

For Each box As Box In BoxList
    ' Now box is typed as Box and not object, so just use it
    box.x
Next

OTHER TIPS

You can create your own custom collection class - this is what we had to do back before generics. This article from MSDN gives you the specifics:

''' Code copied directly from article
Public Class WidgetCollection
   Inherits System.Collections.CollectionBase

    Public Sub Add(ByVal awidget As Widget)
       List.Add(aWidget)
    End Sub
    Public Sub Remove(ByVal index as Integer)
       If index > Count - 1 Or index < 0 Then
          System.Windows.Forms.MessageBox.Show("Index not valid!")
       Else
          List.RemoveAt(index)
       End If
    End Sub
    Public ReadOnly Property Item(ByVal index as Integer) As Widget
       Get
          Return CType(List.Item(index), Widget)
       End Get
    End Property

End Class
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top