
Multiple Constraints | 137
Generics
This is the Title of the Book, eMatter Edition
Copyright © 2006 O’Reilly & Associates, Inc. All rights reserved.
In addition to these two flavors of type constraints (class and interface), the As
clause is also used to establish a new constraint. This type of constraint restricts
the allowed replacement types to only those types that have a parameterless
constructor—that is, a constructor that takes no arguments. To use a new
constraint, add the
As New clause to the type parameter.
Public Class WorkGroup(Of T As New)
This enables the class to create new instances of the type replaced by T within the
class’s source code.
Public Class WorkGroup(Of T As New)
Public Function DoSomeWork( ) As T
' ----- Create a new instance of whatever 'T' is.
Dim result As New T
...
Return result
End Function
End Class
Because the As New clause prepares the class to create an instance of the type
defined by the type parameter, you cannot specify any type for the type parameter
that includes the
MustInherit keyword. Such classes cannot be instantiated, and it
would be meaningless (and an error) to use them with the
New keyword.
Each defined type parameter can include a different constraint, the same
constraint used with other type parameters, or no constraint at all. In this state-
ment, T1 has no constraints placed on it, but the other type parameters do.
Public Class WorkGroup(Of T1, ...