The first topic I would like to talk about is .NET Generics. This language feature was introduced in .NET 2.0, and I think it’s one of the more useful new language features introduced in 2.0. It’s available in both VB.NET and C#, but I’ll be provided the examples here in VB.NET.
What are Generics? Basically generics are a way to make classes that can work with multiple data types, but that can be declared to use a specific type at run time. I will use a classic example to illustrate this.
One of the more useful classes in the .NET Framework is the Arraylist class. This class works pretty much like a standard array, but it allows you to dynamically add new items without having to manually re-size it. One potential downside to the Arraylist is the it’s weakly typed, meaning you can insert any type into it, and each element in an Arraylist can contain a different type. Sometimes this might be useful, but most of the time you want every item in the array to be the same type.
One way to fix this is to build a strongly type wrapper class around the Arraylist. Here is the example code for a strongly type Date Arraylist:
This works just fine, but it would start getting a little redundant if you had to do a lot of these for different types.
Generics provide an easy solution to this problem. Here is the code for the Generic version:
You will notice the biggest difference is the class declaration. The phrase “Of itemType” is saying that this class is going to be using a type that is specified at the time of declaration and we will call this type itemType. You can think of itemType as a placeholder for the actual type the class will use. We use itemType in the class anyplace we would have used Date in the previous example. So you will see in the declaration of the Add Sub that we are declaring the parameter item as type itemType.
To use this class we would create an instance of it like this:
Dim list As New TypedList(Of Date)
When our TypeList object is created everyplace where we had itemType will essentially be replaced with Date. We now have a strongly typed Arraylist of dates. If we try to insert something other then a date an exception will be thrown at runtime.
You are not restricted to using one type in a Generic class. Here is an example of how you could do a strongly type Hashtable
You can see in the declaration of the class that we provide two types, one for the key and one for the item. To create an instance of this class so that the key would be an integer and the item to be a string you would do this:
Dim table As New TypedHastable(Of Integer, String)
The examples I have shown here are a good illustration of how generics work, but really aren’t necessary since the .NET Framework actually has generic versions of the major collection types build in. I’ll talk about these in my next post along with the C# generic syntax.
0 Komentar