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, indices between 0 and 9 (inclusive bounds) can be used:

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

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

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 typically passed together with the array (or in lower-level terms for those languages, a pointer) for the recipient to do proper bounds checking. Bugs ...

Get C# 4.0 Unleashed 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.