ASP.NET: Using Generics to create a property list
From Wiki
Summary: An example of how the System.Collections.Generic namespace can allow us to create a Property which can be added to, referred to by index and also iterated.
I recently came across a situation where I wanted to add a list of objects to a class and then refer to them by index. The System.Collections.Generic namespace came to the rescue, specifically via it's List Generic class.
To demonstrate the situation, imagine we have a box which can contain multiple files. Firstly, I'd need to create a box class (perhaps with an ID so that we can reference it later) and then I'd need a Files property to which I could add multiple files. I'll also have to create a File class which I'll add an ID to as well.
To represent this in code, we would create a File class with one property for the ID e.g.
- Public Class File
- Sub New(ByVal ID As Integer)
- _FileID = ID
- End Sub
- Public Property FileID() As Integer
- Get
- Return _FileID
- End Get
- Set(ByVal value As Integer)
- _FileID = value
- End Set
- End Property
- Private _FileID As Integer
- End Class
Then, we need to look at how we create our Box class and this is where the Generics come in. Unlike our File class above, we need to be able to create a list of files rather than just one variable such as the ID. To do this, we can use the List class and the IList interface. When we create our Files property we need to tell it that it is actually a list and also what the list contains. In this case it will contain a list of our Files class e.g.
- Imports System.Collections.Generic
- Public Class Box
- Sub New(ByVal ID As Integer)
- _BoxID = ID
- _Files = New List(Of File)
- End Sub
- Public Property BoxID() As Integer
- Get
- Return _BoxID
- End Get
- Set(ByVal value As Integer)
- _BoxID = value
- End Set
- End Property
- Public Property Files() As IList(Of File)
- Get
- Return _Files
- End Get
- Set(ByVal value As IList(Of File))
- _Files = value
- End Set
- End Property
- Private _BoxID As Integer
- Private _Files As IList(Of File)
- End Class
Now, if I want to create a new box and add some files to it, I can do so very easily like this:
- ' Create a box
- Dim b As New Box(1)
- ' Add a few files
- b.Files.Add(New File(1))
- b.Files.Add(New File(2))
- b.Files.Add(New File(3))
Also, if I need to go back and reference a file by it's index I can do so like this:
- ' Get a file by index
- Dim myFile As File
- myFile = b.Files(2)
And, if needed, I can loop through the entire list of files:
- ' Loop through the collection of files
- For Each f As File In b.Files
- Response.Write(f.FileID)
- Next
This Hack is part of the ASP.NET Hacks collection


