Professional .NET 2.0 Generics
Tod Golding
Professional .NET 2.0 Generics
Tod Golding
Copyright © 2005 by Wiley Publishing Inc. All rights reserved.
Published by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form
or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except as
permitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior
written permission of the Publisher, or authorization through payment of the appropriate per-copy fee
to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax
(978) 646-8700. Requests to the Publisher for permission should be addressed to the Legal Department,
Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317)
572-4355,or online at />LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR
MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR
COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL
WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE
SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT
THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A
COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOT
THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN
ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A
POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR
THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY
PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE
THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED
BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317)
572-4002.
Trademarks: Wiley, the Wiley Publishing logo, Wrox, the Wrox logo, and Programmer to Programmer
are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates. All other
trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with
any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print
may not be available in electronic books.
Library of Congress Cataloging-in-Publication Data
ISBN-13: 978-0-7645-5988-4
ISBN-10: 0-7645-5988-5
Printed in the United States of America
10
9
8
7
6
5
4
3
2
1
About the Author
Tod Golding has 20 years of experience as a software developer, lead architect, and development manager for organizations engaged in the delivery of large-scale commercial and internal solutions. He has
an extensive background leveraging .NET, J2EE, and Windows DNA technologies, which has allowed
him to become equally skilled with C#, Java, and C++. Tod has worked and consulted at a variety of
companies, including stints with Microsoft and Borland.
Tod has a B.S. in Computer Science from California State University, Sacramento. He started his writing
career as a journalist for the Sacramento Bee daily newspaper. Prior to this book, he was also a contributing
author for the XML Programming Bible, another Wiley publication. Tod currently resides in Sacramento,
California, where he owns and operates Blue Puma Software.
Credits
Vice President and Executive Group Publisher:
Development Editor:
Richard Swadley
Sharon Nash
Vice President and Publisher:
Production Editor:
Joseph B. Wikert
Felicia Robinson
Acquisitions Editor:
Technical Editor:
Jim Minatel
Mark A. Strawmyer
Editorial Manager:
Text Design & Composition:
Mary Beth Wakefield
Wiley Composition Services
Senior Production Editor:
Tim Tate
Acknowledgments
Even though my name stands alone on the cover of this book, it certainly couldn’t have come to life
without the support, encouragement, hard work, and creative input of many others.
My family has to be at the top of the list of those that deserve thanks. The sacrifices made by my wife,
Janine, during the past year were nothing short of heroic. Her support never waned, and I could not
have finished this project without her. Thanks, too, to my children, Chelsea and Ryan, who always
showed interest in my progress. Their smiling faces were always a great source of inspiration.
I’d also like to thank everyone at Wiley Publishing. Without Jim Minatel’s insight and guidance, this
book could not have gotten off the ground. His flexibility and willingness to work with a moving target
provided me with the freedom this topic needed. I also can’t go without mentioning Wiley’s Sharon Nash
and Felicia Robinson, who managed all the logistics associated with editing this book. Thanks, too, to
Mark A. Strawmyer for all of his contributions on the technical editing front.
There are also all those who helped push me along during the genesis of this book. My long-time friend,
Bill Clark, provided perspective and creative influence that helped shape my approach to generics.
Finally, special thanks go to Mike Cohn, who has always pushed me to take on new challenges. His early
prodding and mastery of the 100-hour workweek clearly had the single greatest impact on getting me
moving on this project.
Contents
Acknowledgments
Introduction
Chapter 1: Generics 101
Why Generics?
Enter Generics
Hello Generics
A More Conceptual View
Terminology
Type Parameters
Open Types
Constructed Types
Type Arguments
Open and Closed Constructed Types
Generic Methods
Type Instantiation
Arity
Generic Types
Bringing It All Together
Summary
Chapter 2: Valuing Type Safety
Motivation
Least Common Denominator Programming
A Basic Example
Applying Generics
Casting Consequences
Interface Type Safety
Scratching the Surface
Safety vs. Clarity
Summary
Chapter 3: Generics ≠ Templates
Shared Concepts
Run-Time vs. Compile-Time
v
xv
1
1
7
10
12
14
14
15
15
15
15
16
16
17
17
17
17
19
19
20
21
26
29
31
32
32
33
35
35
36
Contents
Compile-Time Instantiation (Templates)
Run-Time Instantiation (Generics)
Lost in Translation
The Brouhaha
Code Bloat
Assemblies and Type Equivalence
Templates Extras
Template Specialization
Non-Type Parameters
Type Parameter Inheritance
36
37
38
42
42
42
43
43
44
44
Cross-Language Support
Debugging
Mix and Match Nirvana
Summary
44
44
44
45
Chapter 4: Generic Classes
47
Parameterizing Types
47
Type Parameters
Overloaded Types
Static Constructors
49
50
51
Inheritance
Protected Members
Fields
Static Fields
Constructed Fields
Methods
52
55
56
57
59
60
Overloading Methods
Overriding Methods
Arrays of Type Parameters
Operator Overloading
61
63
65
66
Nested Classes
Consuming Generic Classes
67
69
Accessibility
The Default Keyword
System.Nullable<T>
Accessing Type Info
Indexers, Properties, and Events
Generic Structs
Generic Interfaces
Summary
viii
70
73
74
76
77
80
81
82
Contents
Chapter 5: Generic Methods
The Basics
A Deeper Look
Apply Constraints
Type Parameter Names
Overloading Generic Methods
Uniqueness with Generic Classes
Constraints and Uniqueness
Overriding Generic Methods
Type Inference
Generic Methods and Delegates
Type-Safe Database Access Example
Summary
Chapter 6: Generic Delegates
Delegate Basics
Adding Generics to the Equation
Event Handling
Generic Delegates with Generic Methods
Delegates in the Framework
Action<T>
Comparison<T>
Converter<T, U>
Predicate<T>
Choosing Your Delegates
Type Coercion
Applying Constraints
Delegates and Anonymous Methods
Summary
Chapter 7: Generic Constraints
Overview
Constraint Types
Interface Constraints
Class Constraints
Generic Types as Constraints
Constructor Constraints
Boxing and Constraints
83
83
85
87
88
88
90
91
92
95
96
97
98
99
99
102
105
106
106
106
107
107
107
107
107
108
109
109
111
111
115
115
116
117
118
119
ix
Contents
Using Multiple Constraints
Ambiguous Constraints
Ambiguity When Mixing Classes and Interfaces
Generic Delegate and Method Constraints
Inheritance and Constraints
Are Generics Generic?
Summary
Chapter 8: BCL Generics
Motivation
The Big Picture
Generic Collection Interfaces
Classes
System.Collections.ObjectModel
Enumerators
Using Delegates
Generic Collection Classes
Collection<T>
Comparer<T>
Dictionary<TKey, TValue>
EqualityComparer<T>
KeyedCollection<TKey, TItem>
LinkedList<T>
LinkedListNode<T>
List<T>
Queue<T>
ReadOnlyCollection<T>
SortedDictionary<TKey, TValue>
SortedList<TKey, TValue>
Stack<T>
BindingList<T>
Testing Equality
Null Collection Elements
More to Come
Summary
Chapter 9: Reflection, Serialization, and Remoting
Reflection
Working with Open and Closed Types
Extending System.Type
Determining if a Type Is Generic
x
122
123
124
125
126
127
128
129
129
130
130
132
133
133
134
134
134
147
149
157
159
160
161
162
175
177
179
182
183
184
184
185
185
185
187
187
188
188
188
Contents
Creating Open and Closed Types with Reflection
Converting Closed Types to Open Types
Examining Parameters and Arguments
Reflection and Generic Inheritance
Reflecting on Generic Methods
Obfuscation Reminder
Serialization
Serialization Basics
Custom Serialization
Serialization with Web Services
Remoting
Summary
189
194
195
198
199
201
202
202
204
208
211
215
Chapter 10: Generics Guidelines
217
An Evolving List
Defining Guidelines
Organization
Identifying Generic Opportunities
217
217
218
218
Item
Item
Item
Item
Item
1:
2:
3:
4:
5:
Use Generic Collections
Replace Objects with Type Parameters
Replace System.Type with Type Parameters
Use Type Parameters for Ref Types (C# Only)
Genericize Types That Vary Only by a Data Type
Balancing Readability with Expressiveness
Item 6: Use Expressive, Consistent
Type Parameter Names
Item 7: Use Aliasing for Complex or Frequently Used Types
Item 8: Don’t Use Constructed Types as Type Arguments
Item 9: Don’t Use Too Many Type Parameters
Item 10: Prefer Type Inference with Generic Methods
Item 11: Don’t Mix Generic and
Non-Generic Static Methods
Using BCL Generic Types
Item 12: Custom Collections Should Extend Collection<T>
Item 13: Use the Least Specialized Interface in Your APIs
Item 14: Enable “for each” Iteration with IEnumerable<T>
Applying Constraints
Item
Item
Item
Item
15:
16:
17:
18:
Select the Least Restrictive Constraints
Don’t Impose Hidden Constraints
Avoid Multiple Constraint Ambiguity
Provide Parameterless Constructors
218
219
219
220
221
227
228
231
232
233
233
234
235
235
235
236
236
236
237
237
238
xi
Contents
The Kitchen Sink
Item
Item
Item
Item
Item
19:
20:
21:
22:
23:
Use
Use
Use
Use
Use
Static Data Members with Caution
Interfaces in Lieu of Classes
Comparer<T> for All Type Comparisons
Nullable<T> for Optional Values
EventHandler<T> for All Events
Summary
Chapter 11: Under the Hood
Overview
Assumptions
High-Level Goals
Validate at Declaration
Simplicity
Platform Conformity
Language Agnostic Generics
No Boxing
No Meta-Programming
IL Representation of Generic Types
Specialization and Sharing
Code Specialization
Code Sharing
The .NET Hybrid Model
Just-in-Time Specialization
239
239
240
241
241
241
242
243
243
244
244
244
244
245
245
245
245
246
248
248
248
248
249
Exact Run-Time Types
Support for Polymorphic Recursion
NGen and Generic Types
Performance
Memory Footprint
Backward Compatibility
Summary
254
256
257
259
261
262
262
Chapter 12: Using Generics with C++
263
Templates or Generics?
Blurring the Lines
No Limits
Generic Classes in C++
Consuming Generic Classes
Inheritance
Nested Classes
xii
263
264
264
264
265
266
267
Contents
Methods in Generic Classes
Default Types
Generic Methods in C++
Generic Interfaces in C++
Constraints
Generic Delegates in C++
Mixing Generics and Templates
STL.NET
Summary
268
268
268
270
271
273
274
277
278
Chapter 13: Using Generics with J#
279
J# Generic Limitations
Migrating from Java Generics
Consuming Generic Types
Leveraging Cross-Language Support
Working with Interfaces
Complying with Constraints
Calling Generic Methods
Java Type Arguments
Calling Generic Delegates
Arrays of Generic Types
Summary
279
280
280
281
283
285
287
288
289
289
290
Chapter 14: Power Collections
A Little History
The Big Picture
Base Classes
Containers
Algorithms Class
Generic Structures
Delegates
Class Reference
Algorithms
Bag<T>
BigList<T>
BinaryPredicate<T> (Delegate)
CollectionBase<T>
Deque<T>
DictionaryBase<TKey, TValue>
ListBase<T>
291
291
292
292
293
295
295
296
296
296
321
332
336
336
337
341
342
xiii
Contents
MultiDictionary<TKey, TValue>
MultiDictionaryBase<TKey, TValue>
OrderedBag<T>
OrderedBag<T>.View
OrderedDictionary<TKey, TValue>
OrderedDictionary<TKey, TValue>.View
OrderedMultiDictionary<TKey, TValue>
OrderedMultiDictionary<TKey, TValue>.View
OrderedSet<T>
OrderedSet<T>.View
Pair<TFirst, TSecond >
ReadOnlyCollectionBase<T>
ReadOnlyDictionaryBase<TKey, TValue>
ReadOnlyListBase<T>
ReadOnlyMultiDictionary<TKey, TValue>
Set<T>
Triple<TFirst, TSecond, TThird>
343
345
346
349
350
354
354
355
355
358
358
358
359
360
361
362
366
Additional Libraries
Summary
367
367
Index
369
xiv
Introduction
Although generics are new to .NET platform, the concepts that motivated their introduction have been
around for years. However, while their value was often acknowledged, they were frequently stereotyped
as being highly complex, unwieldy, and unapproachable. This reputation always seemed to obscure
their value and limit their ability to capture the mindshare of the broader population of developers. The
real truth here, though, is that generics simply couldn’t become truly mainstream without first having
more languages and environments add support for generics. And, prior to version 2.0 of the .NET
Framework, Visual Basic, C# and J#, developers were unable to use any generic constructs. As a result,
many of these developers remained unaware of the power and value of generics. You can’t miss something if you’ve never had it.
Now, with .NET Framework adding full support for generics, this dynamic will certainly change. And,
as generics begin to move out of the shadows and into the limelight, you’re going to want to be in a
position to maximize their value in your own solutions. To get to that point, though, you’ll need to
understand all the nuances associated with creating and consuming generics, how they reach their way
into and influence the fabric of the .NET Framework.
The overriding goal of this book, then, is to provide a soup-to-nuts blend of basic syntax, key concepts,
and examples of generic libraries that will provide you with a foundation that will help you determine
how and when you might want to start leveraging generics. And, as you get more familiar with generics
and you start understanding some of their obvious—and not so obvious—implications, it’s likely you’ll
also find yourself leveraging generics much more heavily than you may have ever expected.
Not Just Syntax Candy
Developers often look at new language features with a bit of skepticism. Every time some new twist is
added to a language, there are those who seem to want to minimize its impact. You can look at nearly
any language feature and pick it apart. Do you really need overloaded methods, for example? You certainly could create separate method names for each signature and achieve the same result. That’s not the
point, though. To reduce the argument to that level is to miss the underlying relevance of the feature.
The presence of overloaded methods impacts the way clients interact with your class and has a direct
impact on the readability, usability, and maintainability of your code.
xv
Introduction
This same logic should be applied when considering generics. Do you really have to use generic containers? No. All the old System.Collections types, with all their glaring type-safety and efficiency flaws,
are still right there for you to use. The question is: why would you continue to use them in the presence
of generics? Perhaps there are compatibility issues or other forces that may require you to use non-generic
types. Those conditions aside, though, there’s no real valid argument for using a non-generic container
in place of its generic equivalent.
My point here is that generics are more than just some new, optional way to parameterize your types. If
you drink the Kool-Aid (and you should), you’ll find generics influencing your entire approach to how
you create and consume types. At a minimum, you’ll find yourself raising your type-safety expectations.
Overcoming Stereotypes
C++ templates, perhaps the most widely used generic implementation, have a reputation among many
developers for adding complexity and reducing readability. This reputation, justified or not, seems to
lead some to conclude that supporting generics in any language somehow compromises the syntactic
elegance of that language. There’s this notion that generics makes your code appear as though it has
been run through an encryption algorithm.
So, as generics were coming onto the scene, there were many who seemed to be of this mindset. They
mapped C++ templates onto generics and immediately assumed that the addition of parameterized
types somehow has undermined the quality of some of the .NET languages. This, from my perspective,
seems to be an unfair mapping.
The .NET implementation of generics certainly shares some syntactic elements with C++ templates. As
you look at generics in more detail, you should find that generics—by their very nature—do not promote the same level of obfuscation that is sometimes found within C++ templates. This limits their
power, but it also limits their impact on readability and maintainability.
Approaching Generics
A number of different approaches can be taken when tackling a topic of this nature. Some books will
take a more specification-oriented angle where topics are tackled from an almost lexical perspective.
Others books will take a more conceptual view and focus more on providing examples of what’s valid
without trying to recite, precisely, which syntax patterns are valid.
For this book, I definitely lean more toward the conceptual model. My goal here is to expose you to all
the elements of generics without necessarily exploring every permutation of syntax that is possible. My
goal here is to get developers to see the broader implications of generics, and that will be most successfully achieved through a detailed examination of the key conceptual aspects associated with creating
and consuming generic types.
What Does This Book Cover?
Professional .NET 2.0 Generics represents a soup-to-nuts, detailed look at all the facets of generics, providing developers with a comprehensive view of what can be achieved through the application of generics.
xvi
Introduction
The contents of the book fall into some logical categories. The book starts out with a series of chapters
that are focused primarily on the conceptual aspects of generics. Although these chapters use .NET
generics to convey these concepts, they’re really more broadly applicable to anyone who might be interested in understanding the overall value of using generics.
Beyond the conceptual, the book then moves on to a series of chapters that are dedicated to exploring
the specific syntactic mechanics of using .NET generics. These chapters look at all the ways generics are
applied to classes, methods, delegates, and so on and explore all the rules that govern their declaration
and consumption.
Once coverage of the mechanics are completed, the book then turns its attention to those libraries that
will provide you with some of the fundamental, out-of-the-box types that typically come with any environment that supports generics. The book addresses this with two chapters that explore the BCL generic
types that are included with the .NET Framework and a third-party library that provides even more
standard generic types that you’re likely to find yourself leveraging in your own code.
To round things out, the book also examines some of the broader generic issues, including generic guidelines, a comparison with C++ templates, and a peek under the hood of the .NET generics implementation.
Who Is This Book For?
This book is targeted at a fairly wide spectrum of developers. Certainly, its broadest appeal will be those
developers who are first-time generic programmers. That population of developers will extract the most
benefit from the full range of topics I’m targeting here, spanning everything from the basic introduction
to syntax and concepts to the libraries and discussion of the underlying mechanics of generics.
The next tier of likely readers are those developers who might be transitioning from C++ templates or
even Java generics. If you fall into this category, you might find yourself more interested in diving
directly into the syntax and reference materials.
Overall, this book should be of value to anyone who wants a more comprehensive understanding of the
features and characteristics of the .NET implementation of generics. Even if you’re not a .NET developer,
you may find generic topics here that are of value to you.
While this book is targeted at a fairly broad audience, it is not likely to be appropriate for anyone that is
relatively new to the field of computer science. Generics will simply be too difficult to tackle if you don’t
have a firm handle on basic object-oriented programming concepts and techniques.
Language Considerations
As a CLS-compliant feature, generics are supported under C#, Visual Basic, C++, and J#. And, as is the
case for many .NET authors, there is always the issue of how to address a technology that spans all these
languages without diving deeply into the syntactic nuances of each one. This is especially true with
something like generics, where the generic syntax between, say, VB and C#, varies quite a bit.
These realities, coupled with my strong belief that you need to see examples in your language of preference, led me down the path of showing examples in both Visual Basic and C#. My logic was based on
xvii
Introduction
the fact that these two languages appear to be two of the more popular among .NET developers and
are also likely to be the languages where there will be the largest population of first-time generics
programmers.
Throughout this book, then, you will notice that I have provided side-by-side examples in both Visual
Basic and C#. And, to round things out, I’ve also included separate chapters on C++ and J#, pointing out
the specifics of each of these two languages. C++ is especially interesting, because it allows you to leverage a combination of both templates and generics.
Synopsis
The sections that follow give you an overview of each of the chapters of the book, providing a snapshot
of the fundamental role each chapter plays in the overall landscape of the book. This breakdown should
provide you with a clear view of what the book covers and what materials are best targeted at your specific needs.
Chapter 1: Generics 101
This chapter is a basic generics primer. It lays out all the fundamental building blocks of generic concepts, allowing first-time generics developers to establish a solid generics foundation that serves as the
basis for much of what appears in the ensuing chapters. The focus of this chapter is more on the underlying concepts that make generics necessary and less on the detailed mechanics of working with generic
types. If generics are completely new to you, you need to start here.
Chapter 2: Valuing Type Safety
This book is littered with references to the value and importance of type safety. To appreciate generics is
to appreciate type safety. This chapter builds on the concepts that are established in Chapter 1, exploring
the basic elements of type safety that we’ve all been forced to live with outside the world of generics.
The goal here is to provide a clear illustration of how and why developers should value type safety and
explain how generics can improve the overall type safety profile of their code.
Chapter 3: Generics ≠ Templates
Generics are often confused with C++ templates and, although they share some common heritage and
goals, they are most certainly different. And, before digging into the syntax of generics, it is important to
clarify how generics differ from templates. Naturally, if you’ve never dealt with templates before (and
never plan to) this distinction will be of little value. However, if you’ve come from a C++ background,
you’ll want to be very clear about how these differences might affect your overall approach to the .NET
generics implementation.
Chapter 4: Generic Classes
A big part of the value of generics is having the ability to introduce your own generic types (or extend
existing generic types). As such, it’s vital that you have a good grasp of what is involved in the definition of generic classes. This chapter’s look at generic classes should help to crystallize the true power of
xviii
Introduction
what can be achieved with generics. It explores all the facets of how generics influence the signature and
implementation of a type. Overall, this chapter should cover all the traditional topics that are associated
with non-generic classes, including a look at how inheritance and polymorphism are implemented using
generic types.
Chapter 5: Generic Methods
With generic classes out of the way, the book then turns its attention to the more subtle, less complex
area of generic methods. This chapter is focused on highlighting the overall utility and power that can be
achieved through making a method generic. In fact, some of the most immediate and useful applications
of generics will likely be made through the use of generic methods. So, even though they’re relatively
straightforward, it’s important to see what, conceptually, they enable.
Chapter 6: Generic Delegates
Delegates are one of the more heavily used features of the .NET platform, and they are also one of the
most obvious areas where generics allow you to simplify your code. This chapter looks at how the concept of delegates is naturally extended through generics, allowing single delegates to replace all the
various permutations of delegates you might have previously required. Once you’ve been exposed to
the simplicity and type safety of generic delegates, you may never use a non-generic delegate again.
Chapter 7: Generic Constraints
At this stage in the book, you already will have been exposed to many common applications of generics.
You will now be at a point where you’ll need to consider how to add more specificity to the parameters
that are supplied to your generic classes, methods, delegates, and so on. This chapter provides a detailed
view of how constraints are applied to your type parameters to achieve this goal. Constraints are a core
concept to .NET generics, and they have significant influence on how you will approach the design and
interface of your type hierarchies.
Chapter 8: BCL Generics
This chapter provides a comprehensive view of all the generic types that are included as part of the
.NET Framework’s Base Class Library (BCL). Although this chapter largely serves as a reference, it also
provides a conceptual view of the namespace. This conceptual view will give you a much better understanding of how and when each of these generic types can be employed in your own solutions. As part
of this, the chapter also discusses how you might extend these classes and introduce your own, derivative types. The chapter is filled with examples that exercise many of the key features of each type.
Because you’re likely to be using many of these classes in place of the old, non-generic versions, it’s
important to familiarize yourself with the basics of this library.
Chapter 9: Reflection, Serialization, and Remoting
Generics also reach into other areas of the .NET platform. This chapter looks at three key areas of the
platform that were modified or improved via generics. Specifically, the chapter examines how .NET’s
reflection, remoting, and serialization are influenced by generics. The generic elements of each of these
areas are explored with examples that highlight the key areas that deserve special, generic attention.
xix
Introduction
Chapter 10: Generics Guidelines
With the introduction of any new language feature also comes the need for guidelines that provide some
rules and conventions for how that feature should be applied. Generics are no different. They, too, come
with an ever-growing list of guidelines that shape their usage. This chapter looks at this evolving area,
providing developers with a compilation of those guidelines that are emerging in the area of generics.
The chapter provides a point-by-point breakdown of each guideline and explains the rationale that motivated its creation.
Chapter 11: Under The Hood
Understanding the syntax and concepts of generics isn’t really enough. If you’re really going to understand their efficiencies and behavior, you’ll need to dig deeper. That deeper, “under the hood view” of
generics is the focus of this chapter. The chapter looks at how the CLR manages all aspects of generic
types and explains how .NET is able to represent generic types at run-time. This discussion also includes
a look at some basic benchmarks that highlight the run-time efficiencies that can be achieved with
generic types.
Chapter 12: Using Generics with C++
The examples throughout the other chapters in this book are focused entirely on using generics with
Visual Basic and C#. However, the concepts in these chapters apply to any of the .NET languages that
can create or consume generic types. And, each of these other languages includes its own set of generic
nuances. This chapter looks, specifically, at how the C++ language can be used with generic types. This
chapter also discusses how generic types can be mixed with C++ templates in a way that offers C++
developers the best of both worlds.
Chapter 13: Using Generics with J#
Just as Chapter 12 looked at the nuances of C++ with generic types, this chapter looks at how developers
can employ generics as part of the J# code. It looks at how all the fundamental types are used with J#,
explaining the syntax variations and exploring some of the generic limitations imposed within J#.
Chapter 14: Power Collections
Since the introduction of generics, developers have been scrambling to create new, third-party libraries,
many with overlapping goals. Among these, the Power Collections library appears to have the most
momentum and support and, as such, is likely to continue to be a key player in the generic library space.
Given this reality, it made sense to include a complete chapter that provides conceptual and reference
information for this library. Much like Chapter 8, this library includes comprehensive coverage of all the
types in the library along with examples that exercise its more interesting interfaces.
Conventions
Throughout this book, you will find that the text conforms to a common set of conventions. This following represent some of the examples of conventions that I have followed accompanied by an explanation
of their meaning:
xx
Introduction
Boxes like this one hold important, not-to-be forgotten information that is directly
relevant to the surrounding text.
All code examples are highlighted with a gray background with a heading that
designates the language being employed in the example.
As for styles in the text:
❑
Any code that appears within text or any reference to a namespace is shown as follows:
MyClass<T> or System.Collections.Generic.
❑
Emphasized words are shown in italics.
❑
All generic types appearing within the text use the C# representation. So, a generic class would
appear as: MyClass<T>.
Source Code
All of the source code for this book is available at the Wrox Press Web site, which is located at
. This site should provide you with a clear path to source code for all the
Wrox books. Just locate the title of this book and you should be all set.
Generally speaking, the examples should match precisely what you see in the book. You’ll also come
across some scenarios where the example directories have a superset of what’s in the book. These examples typically just represent additional scenarios that were outside the scope of what ended up being
included in the text.
Errata
I’d like to think this book is 100% bug free. However, as a developer, I know just how unlikely that is.
There are certainly going to be mistakes that find there way into any book. And, while I hope the list of
issues is short, there still needs to be a centralized location for capturing these errors so they can be
shared with the rest of the development community.
For Wrox books, this information is all captured through the www.wrox.com Web site. Simply look up
this book and, once you locate it, select the “errata” link. This will allow you to both report and view the
errata for this book.
p2p.wrox.com
In the true spirit of the programmer-to-programmer motto, Wrox maintains a series of forums at
p2p.wrox.com where members of the development community share ideas and opinions. You’ll discover everyone from authors to editors contributing content and generally interacting in these forums.
They provide a great avenue for exchanging ideas.
xxi
Generics 101
For many programmers, generics will be an entirely new language feature. As such, it is important
to establish a foundation of concepts that will clarify the role and significance of generics in the
overall scheme of the .NET platform. This chapter provides this fundamental, conceptual view of
generics that should provide you with a solid base of ideas that can be built upon in the chapters
that follow. Along the way, you’ll get the opportunity build your first generic types and get some
exposure to the basic mechanics of generic types. This chapter also introduces a set of new terms
that are used when referring to common generic concepts. You’ll need to have a clear understanding
of these terms because they are used throughout the book. Naturally, if you’re already comfortable
with the basics of generics, you may want to skip over this chapter.
Why Generics?
Most programmers can point to that one moment in their career where the light of abstraction or
generalization went off in their head. If you have a background in structured programming, this
might have been uncovered during a foray into the world of function pointers. Or, maybe it just
occurred to you one day when you discovered you could extend the functionality of one of your
methods by parameterizing some aspect of its behavior. If you’re from the OO crowd, this probably happened one day when you stumbled upon your first real good use for polymorphism. At
that moment, whenever it was, you realized that goal of generality, extensibility, and reusability
that everyone had been evangelizing.
Now, with generics, you have an opportunity to wrap your brain around another form of generalization. This new brand of generalization will provide you with a host of new concepts to toss into
your proverbial bag of coding and design techniques. And, once you’ve mastered generics, you
may find yourself wondering how you lived without them for so long.
To understand the fundamental value of generics, you really need to see a compelling example.
Let’s start with a sample of some code that you might write without generics. Suppose you’ve