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 use a generic class with more than one data type. For example, if you have built a generic PriorityQueue class, you can make a PriorityQueue holding Employee, Customer, Order, or Objection objects. Without generics, you would need to build four separate classes to build strongly typed priority queues for each of these types of objects. Reusing this code makes it easier to write, test, debug, and maintain the code.

The main disadvantage to generics is that they are slightly more complicated and confusing than non-generic classes. If you know that you will only ever need to provide a class that works with a single type, you can simplify things slightly by not using a generic class. If you think you might want to reuse the code later for another data type, it’s easier to just build the class generically from the start.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.92.234