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, ints, 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) and it's still type-safe like an array, without nongeneric costs. It's the superarray. (I explain type-safety and the costs of nongeneric collections next.)

Generics come in two flavors in C#: the built-in generics, such as List<T>, and a variety of roll-your-own items. After a quick tour of generic concepts, this chapter covers roll-your-own generic classes, generic methods, and generic interfaces and delegates. ...

Get C# 2010 All-in-One For Dummies® 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.