Appendix L Collection Classes

This appendix provides information about collection classes.

Arrays

Arrays are relatively simple collection classes that enable you to store and retrieve items by using their indexes in the array. C# provides two kinds of arrays: simple arrays and array objects that are instances of the Array class.

Simple Arrays

The syntax for declaring and allocating a one-dimensional array follows.

type[] name = new type[length];

Here type is the data type that the array should hold, name is the name you want to give the array, and length is the number of items the array should hold. The array’s indexes range from 0 to length - 1.

The syntax for declaring and allocating a two-dimensional array follows.

type[,] name = new type[length1, length2];

The only difference between this declaration and the preceding one is that you need to specify the number of items the array should hold in each dimension. For example, the following statement creates an array of integers with 10 rows and 20 columns.

int[,] values = new int[10, 20];

To make higher-dimensional arrays, use a similar syntax with more commas in the declaration and more lengths in the allocation part.

To initialize an array when it is declared, include the values it should hold inside braces, as in the following code.

int[] primes = { 2, 3, 5, 7, 11 };

To initialize multidimensional arrays, include each dimension’s values inside their own braces. The following code declares and initializes a 2 4 array of integers. ...

Get C# 5.0 Programmer's Reference 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.