Object container

labisem

Member
Joined
May 20, 2003
Messages
10
I have a class. Lets say Class Employee. I want to store the instances of this class to a container. A simple solution is an array (Dim a(10) as New Employee), but I want to handle the container dynamic at runtime (for example, to add an instance to the container with a user click).
Which is the best solution?
Ive tried Arraylist:

Dim a As New Arraylist
a.Add(Emp1 As New Employee)

but early binding (Option Strict On) doesnt allow me to handle the instance (for example, a(0).Age)
 
Early binding doesnt stop you, it just means you have to cast your variables explicitly:

Code:
DirectCast(a(0), Employee).MyField
 
Im a great fan of collections myself.

Id build a collection class.
In the only constructor this class will receive a type obejct, against which all futute "add" calls will be checked.

Thats about all. The rest is simply programming a wrapper around a normal collection.

Oh, and probably divil knows a built-in class that does all that :-)
 
Generally I would inherit from one of the Base classes under System.Collections.
IIRC CollectionBase for collections or DictionaryBase for a name / value pair.

It is a fairly simple matter to then provide your own type safe add / remove / item overloads that only deal with the class / interface you desire.
 
A bit rough and ready (no error trapping for example) - but should give you a rough idea

[VB]
Public Class Employee
Public EmployeeName As String
Public EmployeeID As Integer
End Class

Public Class EmployeeCollection
Inherits CollectionBase

Public Function Add(ByVal emp As Employee) As Integer
Return InnerList.Add(emp)

End Function

Public Function Remove(ByVal emp As Employee)
innerlist.Remove(emp)
End Function

Public Function RemoveRange(ByVal index As Integer, ByVal count As Integer)
innerlist.RemoveRange(Index, Count)
End Function

Default Public Property Item(ByVal index As Integer) As Employee
Get
Return DirectCast(innerlist.Item(index), Employee)
End Get
Set(ByVal Value As Employee)
innerlist.Item(index) = Value
End Set
End Property

End Class
[/VB]
 
Thank you all. You were very helpfull. I think that the custom collection its the best solution. The example from PlausiblyDamp was very good.
 
Back
Top