A Real-World Example with Collections

Suppose that 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 ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.