Chapter 5. Collections
Most programs need to deal with multiple pieces of data. Your code might have to iterate through some transactions to calculate the balance of an account, or display recent messages in a social networking web application, or update the positions of characters in a game.
C# offers a simple kind of collection called an array. The CLR’s type system supports arrays intrinsically, so they are efficient, but for some scenarios they can be too basic. Fortunately, the class library builds on the fundamental services provided by arrays to provide more powerful and flexible collection types. I’ll start with arrays, because they are the foundation of most of the collection classes.
Arrays
An array is an object that contains multiple elements of a particular type. Each element is a storage location similar to a field, but whereas with fields we give each storage slot a name, array elements are simply numbered. The number of elements is fixed for the lifetime of the array, so you must specify the size when you create it. Example 5-1 shows the syntax for creating new arrays.
Example 5-1. Creating arrays
int[] numbers = new int[10]; string[] strings = new string[numbers.Length];
As with all objects, we construct an array with the new
keyword followed by the type name, but instead of parentheses with constructor arguments, we put square brackets containing the array size. As the example shows, the expression defining the size can be a constant, but it doesn’t have to be—the second ...
Get Programming C# 5.0 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.