VB2005 Tips and Tricks – part 6

Build Typesafe Generic Classes

Example 1
Public Class GenericList(Of ItemType)
 'Some Code
End Class

Example 2
Public Class GenericList(Of Item Type)
Inherits CollectionBase

Public Function Add(ByVal value as ItemType) as Integer
 Return List.Add(value)
End Function

Public Sub Remove(ByVal value as ItemValue)
 List.Remove(value)
End Sub

Public ReadOnly Property Item(ByVal index as Integer) as ItemType
 Get
  Return CType(List.Item(index),ItemType)
 End Get
End Property

End Class
Program Code
Dim List as New GenericList(Of String)
List.Add("blue")
List.Add("red")

List.Add(Guid.NewGuid()) ' Will be detected by the compiler
Example 3 - More than one type parameter in the class
Public Class GenerichashTable(Of ItemType, KeyType)
 Inherits DictionaryBase
 'Code
End Class
 
Example 4 - Define Constraints to Parameters
Public Class SerializableList(Of ItemType as ISerializable)
 Inherits CollectionBase
 'Code
End Class

Public Class ControlCollection(Of ItemType as Control)
 Inherits CollectionBase
 'Code
End Class

If you want your class to create an instance of the Item
Public Class GenericList(Of ItemType as New)
 Inherits CollectionBase
 'Code
End Class

Example 5 - Define more than one constraint
Public Class GenericList(Of  ItemType as {ISerializable, New})
 Inherits CollectionBase
 'Code
End Class

Generics also works with structures, interfaces, deletates and methods.
 

Comments are closed.