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; } ...
Get Professional .NET 2.0 Generics now with O’Reilly online learning.
O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.