Constraining a Generic Class
When you look at Listing 1, you might begin to wonder how useful generic classes are, because the example class can accept any datatype. Fortunately, you can constrain a generic class to accept only specific datatypes. For example, you might create a datatype class called Address that looks like this:
Public Class Address Public Name As String Public Address1 As String Public Address2 As String Public City As String Public State As String Public ZIP As String End Class
You can constrain the generic class to accept only an Address datatype as input by modifying the declaration. For example, you might want to change the collection in Listing 1 like this:
Public Class MyGenericCollection(Of ItemType As Address)
This generic class will now accept just the Address datatype. Any other use of the class generates an error (the IDE refuses to compile the code). You can use any generic type, as well as interfaces, as a constraint. For example, you might want to define a generic class that only accepts datatypes that implement the ICustomFormatter interface.