Using the Generic Class
Using a generic class in code is only a little different from using any other class. You still have to instantiate the class and you work with the methods, properties, and events as you would any other class. Listing 2 shows a typical example of how to use the generic class defined in Listing 1.
Listing 2 Using a Generic Class
Private Sub btnTest_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnTest.Click ' Create a new collection. Dim CollectInt As New MyGenericCollection(Of String) ' Perform some tasks with it. CollectInt.Add("One") CollectInt.Add("Two") CollectInt.Add("Three") CollectInt.RemoveAt(1) ' Display some statistics. MessageBox.Show("Number of Entries: " + _ CollectInt.Count.ToString()) MessageBox.Show("Value of First Item: " + _ CollectInt(0)) End Sub
The btnTest_Click() method begins by creating a new collection. Notice how the code instantiates the object CollectInt. Instead of the normal method, it requires that the developer provide the datatype of the collection. In this case, the (Of String) entry specifies that this collection will accept only String values.
Once CollectInt is instantiated, the code uses its methods to add and remove values from the collection. There isn't anything different here from the way in which you interact with a standard class, so you really don't need to change any of the techniques you normally use to work with objects based on generic classes.
The code ends by displaying the number of items in the collection and the value of the first item, Two, after using the various methods to manipulate it. Again, you don't have to do anything special to work with the object. The Count property works much as you expect it would. When working with the default property, Item, you'll find that you don't have to perform a conversion to a String as you normally would. The reason is that the IDE and the .NET Framework both know that you created this collection to use a String datatype. In addition, IntelliSense also knows that this is a String datatype, as shown in Figure 1. Notice that you receive String-specific information, rather than a generic datatype, as you would when using Object.
Figure 1 Using generics means getting datatype-specific feedback from IntelliSense.