Single-Dimensional Arrays

Let’s start by having a look at single-dimensional arrays:

int[] squares = new int[10];

This code creates an instance of an integer array of length 10. To set and get elements in the array, you can use indices between 0 and 9 (inclusive bounds):

squares[3] = 9;// ...Console.WriteLine(squares[3]); // prints 9

You’ll see more structured ways (by using loops and eventually using LINQ) to get or set all elements in an array later.

Historically, arrays have been a source of lots of bugs because of the lack of bounds checking. In C and C++, for example, the length of an array is usually passed together with the array (or in lower-level terms for those languages, a pointer) for the recipient to ...

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.