Appendix M

Generics

This appendix summarizes generic classes, extensions, and methods. The final section in this appendix describes items that you cannot make generic.

GENERIC CLASSES

The syntax for declaring a generic class is as follows:

[attribute_list] [Partial] [accessibility] [Shadows] [inheritance] _
Class name [(Of type_list)]
    [Inherits parent_class]
    [Implements interface]
    statements
End Class

All of these parts of the declaration are the same as those used by a normal (non-generic) class. See Chapter 25, “Classes and Structures,” and Appendix K for information about non-generic classes.

The key to a generic class is the (Of type_list) clause. Here, type_list is a list of data types separated by commas that form the generic’s parameter types. Each type can be optionally followed by the keyword As and a list of constraints that the corresponding type must satisfy. The constraint list can contain any number of interfaces and, at most, one class. It can also contain the New keyword to indicate that the corresponding type must provide a parameterless constructor. If a constraint list contains more than one item, the list must be surrounded by braces.

The following code defines the generic MyGeneric class. It takes three type parameters. The first is named Type1 within the generic’s code and has no constraints. The second type, named Type2, must satisfy the IComparable interface. The third parameter, named Type3, must provide a parameterless constructor, must satisfy the IDisposable ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.