O'Reilly logo

Professional .NET 2.0 Generics by Tod Golding

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.1. Overview

To understand the role of generic constraints, you must first have a clear picture of why they're needed and how they are applied. With that as goal in mind, let's get started by building a sample that simply extends an existing generic type. For this scenario, let's assume you've decided to introduce your own DataObjectCollection that will descend from the List<T> collection and add a series of operations that provide specific functionality associated with some data objects from your domain. This new class is implemented as follows:

[VB code]
Public Class DataObjectCollection(Of T)
    Inherits List(Of T)

    Public Sub Print()
        Dim coll As List(Of T).Enumerator = GetEnumerator()
        While (coll.MoveNext())
            Console.Out.WriteLine(coll.Current.ToString)
        End While
    End Sub

    Public Function Lookup(ByVal lookupValue As String) As T
Dim retVal As T
        Dim coll As List(Of T).Enumerator = GetEnumerator()
        While (coll.MoveNext())
            If (coll.Current.ToString().Equals(lookupValue) = True) Then
                retVal = coll.Current
                Exit While
            End If
        End While
        Return retVal
    End Function
End Class
[C# code] public class DataObjectCollection<T> : List<T> { public void Print() { List<T>.Enumerator coll = GetEnumerator(); while (coll.MoveNext()) { Console.Out.WriteLine(coll.Current.ToString()); } } public T Lookup(string lookupValue) { T retVal = default(T); List<T>.Enumerator coll = GetEnumerator(); while (coll.MoveNext()) { if (coll.Current.ToString().Equals(lookupValue) == true) { retVal = coll.Current; break; } ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required