Chapter 8: Buying Generic
In This Chapter
Making your code generic — and truly powerful
Writing your own generic class
Writing generic methods
Using generic interfaces and delegates
The problem with collections is that you need to know exactly what is going in them. Can you imagine a recipe that accepts only the exact listed ingredients and no others? No substitutions — nothing even named differently? That’s how most collections treat you, but not generics.
As with prescriptions at your local pharmacy, you can save big by opting for the generic version. Generics, introduced in C# 2.0, are fill-in-the-blanks classes, methods, interfaces, and delegates. For example, the List<T>
class defines a generic array-like list that’s quite comparable to the older, nongeneric ArrayList
— but better! When you pull List<T>
off the shelf to instantiate your own list of, say, int
s, you replace T
with int
:
List<int> myList = new List<int>(); // A list limited to ints
The versatile part is that you can instantiate List<T>
for any single data type (string
, Student
, BankAccount
, CorduroyPants
— whatever), ...