You make it too complicated .. Net already provides the exact classes you need using Generics.
I want to be able to ... make these calls:
Dim myTin As New TinOfBeans() myTin.Add(New BakedBean(...)) For Each bean As BakedBean in myTin '... Next myTin(0).Flavour = "beany"
Sure. Here's how:
Dim myTin As New List(Of BakedBean)() myTin.Add(New BakedBean(...)) For Each bean As BakedBean in myTin '... Next myTin(0).Flavour = "beany"
Each of your lines accurately displays. Let Generic Collections do the work for you.
You seem to be confused about IEnumerable too, and I have one requirement left:
make calls ... not tied to a particular type of collection
We can use both methods with the same technique. Let it define a method that accepts a Bean collection:
Public Sub CookBeans(ByVal beans As List(Of BakedBean))
However, this does not handle arrays, iterators, or other types of the BakedBean collection. The answer is here: IEnumerable:
Public Sub CookBeans(BvVal beans As IEnumerable(Of BakedBean)) For Each bean As BakedBean In beans Cook(bean) Next End Sub
This time I included an example implementation of the method so that you can see how it will work. Itβs important to understand that this method will allow you to call it and pass in an array, list, iterator, or any other BakedBean collection.
This works because List(Of BakedBean) (or, rather, implements) IEnumerable(Of BakedBean) . Also an array of BakedBean and other .Net collections. IEnumerable is the root interface for all collections. You may have a specific List (Of BakedBean) object in memory somewhere, but specify your method parameters and return types with IEnumerable(Of BakedBean) , and if you ever decide to change this List object to something else , all of these methods will still work.
You can also return IEnumerable:
Public Function GetPintos(ByVal beans As IEnumerable(Of BakedBean)) As IEnumerable(Of BakedBean) Dim result As IEnumerable(Of BakedBean) result = beans.Where(Function(bean) bean.Variety = "pinto") Return result End Function
And if you ever need this IEnumerable to become a list, it's pretty easy:
Dim beans As List(Of BakedBeans) = '... get beans from somewhere Dim pintos As List(Of BakedBeans) = GetPintos(beans).ToList() Cook(pintos)