O'Reilly logo

C# 5.0 Programmer's Reference by Rod Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required