Generics is a new feature of the .Net 2.0 Framework. I've seen many articles on C# using generics, but don't recall seeing many on done for the VB.Net developer. I haven't looked in awhile, so there may be quite a few out there, but I've been meaning to post this for awhile now because its been written and just sitting on my hard drive, so here we go...
Let's consider this overly simplified example below (Note that an array is not really the way you would want to implement an orders collection of sorts, but it works for the concept of generics in this example. This isn't something I would actually implement.)
Public Class Orders
Private myarray(0) As String
Private currentSize As Int32
Public Sub New()
currentSize = 0
End Sub
Public Sub Add(ByVal itemName As String)
If Not myarray.Contains(itemName) Then
If currentSize > UBound(myarray) Then ReDim Preserve myarray(currentSize)
myarray.SetValue(itemName,currentsize)
currentSize += 1
End If
End Sub
End Class
So there we go. You can add orders based on the item name. But what if you wanted to also have a way to add items based on the item number, which is an integer datatype? You would have to create a new class to do so. Now, you could, in the above code, change the
Strings to
Objects, but that uses late-binding and leaves you open to passing any object type, such as a
DateTime into the Add method. This compiles fine, but will throw a runtime exception.
So here is where generics comes in. The
Of keyword becomes your best friend now. The
Of keyword is the same as
<T> in C#. It identifies the data type that should be implemented for the class. So now lets look at our code with generics implemented.
Public Class Orders(Of orderType)
Private myarray(0) As orderType
Private currentSize As Int32
Public Sub New()
currentSize = 0
End Sub
Public Sub Add(ByVal itemName As orderType)
If Not myarray.Contains(itemName) Then
If currentSize > UBound(myarray) Then ReDim Preserve myarray(currentSize)
myarray.SetValue(itemName,currentsize)
currentSize += 1
End If
End Sub
End Class
Now we have a way of creating the orders to class so that we can add items of any type simply by doing the following
Dim itemNameOrders As New Orders(Of String) ' Creates a new orders class to store item names
' Or you can use the next line instead
Dim itemNumberOrders As New Orders(Of Int32) ' Creates a new orders class to store item numbers
And we didn't have to write an entire new class to accomplish this.
Posted
12-21-2004 7:37 AM
by
Raymond Lewallen