How to make VB.Net List class more flexible for the caller

329 views Asked by At

I am new to generics and collections in VB.Net. I've written my first class that creates a list of custom objects. While it seems to work, I believe I've done it in a crude sort of way and I would like to know how to improve it for the code that will need to invoke it. Here is the essential part of the list class:

Public Class Subscribers
    Public List As New List(Of Subscriber)
    Public Sub New()
        Dim sConnDatabase As String = ConfigurationManager.ConnectionStrings("DatabaseConnString").ConnectionString
        Dim connection As New SqlConnection(sConnDatabase)
        Dim cmd As SqlCommand
        cmd = New SqlCommand("SELECT * FROM dbo.Subscriber_v", connection)
        cmd.CommandType = CommandType.Text
        connection.Open()
        Dim objReader As SqlDataReader = cmd.ExecuteReader()
            Do While objReader.Read()
            Dim id As Integer = objReader("SubscriberID")
            Dim s As Subscriber = New Subscriber(id)
            List.Add(s)
        Loop
        objReader.Close()
        connection.Close()
    End Sub
End Class

Here is my first little test for using the class:

Dim n As String
Dim d As Integer

Dim allSubs As New Subscribers()
For Each Subscriber In allSubs.List
    n = Subscriber.SubscriberName
    d = Subscriber.DaysUntilExpired.ToString()
Next

A specific question regarding improvement would be: how to enable the caller to code something like:

For Each x In allSubs
n = x.SubscriberName
d = x.DaysUntilExpired.ToString()
Next

Would there be some way of coding the class such that the allSubs could be expressed without having to also specify .List - and some way of expressing it such that x would be recognized as being of type Subscriber.

1

There are 1 answers

0
JaredPar On BEST ANSWER

To make this work need to have Subscribers implement IEnumerable(Of Subscribers). The implementation can just forward to the List field

Public Class Subscribers Implements IEnumerable(Of Subscriber)
  Public Function GetEnumerator() As IEnumerator(Of Subscriber) _  
    Implements IEnumerable(Of Subscriber).GetEnumerator

    Return List.GetEnumerator()
  End Function

  Private Function GetEnumerator1() As IEnumerable _
    Implements IEnumerable.GetEnumerator

    Return List.GetEnumerator()
  End Function
End Class