Consuming Generic Types
To instantiate and consume generic types, you pass to the constructor the type you want to be handled. For example, the following code creates a new instance of the CustomType
class, enabling it to handle only integers or types that are converted to Integer
via a widening conversion:
Dim integerCollection As New CustomType(Of Integer)(2)integerCollection.Add(0)integerCollection.Add(1)'Writes 1Console.WriteLine(integerCollection(1).ToString)
You pass the desired type to the constructor after the Of
keyword. When invoking the Add
method, you can notice how IntelliSense tells you that the method can receive only Integer
(see Figure 14.1).
Get Visual Basic 2015 Unleashed 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.