VB • Create a Type-Safe Replacement.

Listing 2. Generic container types can serve as a type-safe replacement for unsafe Collection class. After migration, the wizard replaces the VB6 Collection with Microsoft.VisualBasic.Collection. You can improve type safety and eliminate some casting code by replacing Collection class with some generic container from System.Collections.Generic namespace.

‘ Before 
Public Class ShoppingBasket
Private mItems As Collection
		‘...
Public Sub AddItem(ByRef Item As IItem)
mItems.Add(Item, Item.ItemId)
End Sub
Public Sub RemoveItem(ByRef ItemId As String)
Dim Index As Integer
Dim Item As IItem
For Each Item In mItems
Index = Index + 1
If Item.ItemId = ItemId Then
Exit For
End If
Next Item
mItems.Remove((Index))
End Sub
Public Function GetItem(ByVal index As Integer) As IItem
‘DirectCast implemented after Option Strict activated
GetItem = DirectCast(mItems(index), IItem)
End Function
‘Class_Initalize is renamed to Class_Initialize_Renamed and
‘invoked from constructor after the migration 
Private Sub Class_Initialize_Renamed()
mItems = New Collection
End Sub
	‘...


‘ After
Imports System.Collections.Generic
Public Class ShoppingBasket
Private mItems As List(Of IItem)
		‘...
Public Sub AddItem(ByRef Item As IItem)
‘Add method of List accepts single parameter
mItems.Add(Item)
End Sub
Public Sub RemoveItem(ByRef ItemId As String)
Dim Index As Integer
Dim Item As IItem
For Each Item In mItems
Index = Index + 1
If Item.ItemId = ItemId Then
Exit For
End If
Next Item
‘Use RemoveAt method of List instead 
‘of Collection.Remove
mItems.RemoveAt((Index))
End Sub
Public Function GetItem(ByVal index As Integer) As IItem
‘Eliminate DirectCast 
GetItem = mItems(index)
End Function
‘Class_Initalize is renamed to Class_Initialize_Renamed and
‘invoked from constructor after the migration 
Private Sub Class_Initialize_Renamed()
mItems = New List(Of IItem)
End Sub
	‘...