5.9. 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 can be used in the place of multiple, existing 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
[C# code] using System; using System.Collections.Generic; ...

Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.