The concept of "generic objects" in VB.NET is introduced in the article, Generics! Cleaner Data - Faster Code!. Generics extend the power and flexibility of VB.NET in a lot of areas, but you get a bigger performance benefit and more programming options in the generic List object -- List(Of T) -- than with any other. Check out that article to see a performance comparison between ArrayList and the generic List(Of T) doing the same programming task.
To use List(Of T), however, you have to understand how to implement the many methods that the .NET Framework provides. That's what this article is about. I've programmed three examples -- using ForEach, FindAll, and Sort -- to demonstrate how the generic List class works.
As explained in the first article linked above, step 1 is to create a generic List. You can get the data in a lot of ways, but the simplest way is to simply Add it. In this article, I'm going to write code to classify my beer and wine collection! So here's the code to create the collection:
First, I need an object that will represent a bottle from my collection. The code for this is totally standard. Here's my object. (In a Windows Forms application, the Form class has to be first in a file or the Visual Studio designer won't work correctly, so put this at the end.)
Public Class Bottle Public Brand As String Public Name As String Public Category As String Public Size As Decimal Public Sub New( _ ByVal m_Brand As String, _ ByVal m_Name As String, _ ByVal m_Category As String, _ ByVal m_Size As Decimal) Brand = m_Brand Name = m_Name Category = m_Category Size = m_Size End Sub End Class
To build the collection, I Add the items. I put this in the Form Load event.
Dim Cabinet As List(Of Bottle) = _ "New List(Of Bottle) Cabinet.Add(New Bottle( _ "Castle Creek", _ "Uintah Blanc", _ "Wine", 750)) Cabinet.Add(New Bottle( _ "Zion Canyon Brewing Company", _ "Springdale Amber Ale", _ "Beer", 355)) Cabinet.Add(New Bottle( _ "Spanish Valley Vineyards", _ "Syrah", _ "Wine", 750)) Cabinet.Add(New Bottle( _ "Wasatch Beers", _ "Polygamy Porter", _ "Beer", 355)) Cabinet.Add(New Bottle( _ "Squatters Beer", _ "Provo Girl Pilsner", _ "Beer", 355))
All this was standard code in VB.NET 1.0. But note that by defining our own Bottle object, we get the benefits of multiple types in the same collection (in this case, both String and Decimal) and efficient, type safe "late binding".
On the next page, we get to the heart of the matter ... the ForEach, FindAll, and Sort methods.