C# in Depth

Cover of C# in Depth
Order now (3rd edition)

More persuasion on the benefits of generics

Chapter 3: Parameterized typing with generics: 3.1

Created: 5/7/2008
Last updated: 5/7/2008

Joe Albahari provided a good example of where generics really can save you from bugs. While you might not have any problem remembering that everything in a particular ArrayList is an int (boxed, of course) you may find it relatively tricky to find all the accesses if you later change your mind and decide it should actually be full of decimal values. With generics and List<T>, that refactoring exercise is trivial because of the extra checking the compiler can provide. In the risky world of ArrayList you've got to rely on being careful.

Joe also gave another example which he finds usually persuades people of the benefits of generics. Which of these lines would you rather use to find the length of the fourth element of a list?

// When list is an ArrayList
((string) list[3]).Length

// When list is a List<string>