indicated that this method will rely upon type inference to resolve its type parameters. In contrast, the
next two delegate declarations,
d2
and
d3
, supply specific type parameters. For these methods to be
valid, their signatures must match that of the delegate precisely. In the case of
d2
, you achieve this match
by providing matching type arguments (
integer
,
double
, and
string
). The
d3
delegate, on the other
hand, would appear to be a mismatch. However, if you look at the declaration of
DelegateMethod2
more closely, you'll discover that -- even though it accepts three type parameters -- none of those
parameters are referenced in the signature of the method. So, in reality, this method will accept three
parameters of any type.
The last delegate here actually causes a compile error. Its signature appears to match that of the delegate.
However,
MyDelegateMethod3
that is used here does not include any parameters. Thus, even though
three matching types are supplied as type parameters, those type parameters are not referenced in the
method's signature.
Type-Safe Database Access Example
With generic methods, you can bring an additional dimension to the implementation of type safety and
abstraction to your methods. Specifically, through type parameters, you can express information about
the types operated on within your method and the types returned by your methods. You can imagine
that, through the application of type parameters, you'll also identify opportunities where a generic
method might be used in the place of multiple non-generic methods.
Consider a simple scenario where a generic method could be used to satisfy some of these objectives.
In this example, the goal is to create a general
GetItems()
method that could retrieve a collection of
objects from a database. This method might return
Person
,
Customer
,
Employee
, or
Order
objects.
And, with generics, you expect the list returned to be a type-safe collection. The following generic
method achieves these goals:
[VB code]
Imports System.Data.OleDb
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Public Class GetDatabaseItems
Dim dbConn As New OleDbConnection("")
Public Function GetItems(Of T)(ByVal sql As String) As Collection(Of T)
Dim selectCmd As New OleDbCommand(sql, dbConn)
Dim retVal As New Collection(Of T)
Dim dataReader As OleDbDataReader = selectCmd.ExecuteReader()
While (dataReader.Read() = True)
retVal.Add(DirectCast(dataReader(0), T))
End While
Return retVal
End Function
End Class
97
Generic Methods
08_559885 ch05.qxd 9/8/05 11:00 PM Page 97