Generic Classes

Generic classes are a new feature in the .NET Framework and are supported in Visual Basic 2005. A generic class is a single class that provides functionality for different data types, without the need to write a separate class definition for each data type. You can also define generic methods, structures, and interfaces.

A generic class uses type parameters as placeholders for the data types. The code example in Listing 3.10 shows the declaration of a generic class using t to represent the type parameter. You can specify more than one parameter by separating the parameters with commas. When you want to instantiate the class, you must specify the data type, rather than the type parameter, in the declaration, as shown in Listing 3.10.

Listing 3.10. Creating a Generic class Public Class MySampleClass(Of t)

' Implementation code for the class goes here.

End Class

Sub CreateGenericClasses()

Dim myStringClass As New mySampleClass(Of String) Dim myIntegerClass As New mySampleClass(Of Integer)

End Sub

In the System.Collections.Generic namespace, the .NET Framework provides a number of generic collection classes that correspond to existing (nongeneric) collection classes. For example, you can use a Dictionary class to specify the data type for a key-value pair (rather than use a Hashtable), and a List is the generic class that corresponds to an ArrayList.

0 0

Post a comment