A Real-World Example with Collections

Suppose you’re writing an implementation of a list data structure, which maintains a sequential ordering of elements and allows index-based access to its elements. Our collection type provides an improvement over arrays because it allows for the underlying storage to grow when needed. Internally, the most obvious way to implement this is by using an array to store the elements and copy elements to a larger array when storage space is exceeded. So what’s the problem?

Well, with a regular array, you can statically type the array so that it can contain elements of only a certain type:

int[] xs = new int[] { 1, 2, 3 };

This is very convenient as the type is dragged along throughout the code, preventing the user ...

Get C# 4.0 Unleashed 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.