ADVANTAGES OF GENERICS
A generic class takes one or more data types as parameters. An instance of a generic class has those parameters filled in with specific data types such as String, TextBox, or Employee.
For example, you can build a list of OrderItem objects, a hash table containing PurchaseOrders identified by number, or a Queue that contains Customer objects.
Tying generics to specific data types gives them several advantages over non-generic classes:
- Strong typing — Methods can take parameters and return values that have the class’s instance type. For example, a List(Of String) can hold only String values, its Add method can only add Strings to the list, and its Item method returns String values. This makes it more difficult to accidentally add the wrong type of object to the collection.
- IntelliSense — By providing strong typing, a class built from a generic lets Visual Studio provide IntelliSense. If you make a List(Of Employee), Visual Studio knows that the items in the collection are Employee objects, so it can give you appropriate IntelliSense.
- No boxing — Because the class manipulates objects with a specific data type, Visual Basic doesn’t need to convert items to and from the plain Object data type. For example, if a program stores TextBox controls in a normal collection, the program must convert the TextBox controls to and from the Object class when it adds and uses items in the collection. Avoiding these steps makes the code more efficient.
- Code reuse — You can ...