views:

2330

answers:

2

I want to create a collection in VB.NET, but I only want it to accept objects of a certain type. For example, I want to create a class called "FooCollection" that acts like a collection in every way, but only accepts objects of type "Foo".

I thought I could do this using generics, using the following syntax:

    Public Class FooCollection(Of type As Foo)
        Inherits CollectionBase

        ...

    End Class

But I get an error when I compile it that I "must implement a default accessor", so clearly there's something missing. I don't want to specify the type it accepts when I instantiate - I want the FooCollection itself to specific that it only accepts Foo objects. I've seen it done in C# with a strong-typed list, so maybe all I'm looking for is VB.NET syntax.

Thanks for your help!

EDIT: Thanks for the answer. That would do it, but I wanted to have the classtype named a certain way, I actually accomplished exactly what I was looking for with the following code:

Public Class FooCollection
    Inherits List(Of Foo)

End Class
+5  A: 

Why don't you just use a List(Of Foo)... It is already in VB.NET under System.Collections.Generic. To use, simply declare as such:

Private myList As New List(Of Foo) 'Creates a Foo List'
Private myIntList As New List(Of Integer) 'Creates an Integer List'

See MSDN > List(T) Class (System.Collections.Generic) for more information.

Andrew Moore
A: 

You needed to implement a default property for the collection like this:

Default Public Property Item(ByVal Index As Integer) As Foo
Get
  Return CType(List.Item(Index), Foo)
End Get
Set(ByVal Value As Foo)
  List.Item(Index) = Value
End Set

End Property

Jeff Cope