Summary
An array is an indexed collection of objects, all of the same type.
You declare an array by giving the type of objects the array contains, followed by the square bracket operator (
[]), followed by the name of the array. You then instantiate the array with thenewkeyword and the number of elements the array will contain.The index of the first element in the array is always zero, and the index of the last element in the array is always
Length-1.You can use a
forloop to iterate through the array, by using the loop’s counter as the index to the array.The
foreachstatement allows you to iterate through the items in the array (or any other collection) without the need for a counter.The elements of an array can be initialized when the array is created by providing the values of the members in curly braces (
{}).The
paramskeyword lets you pass an arbitrary number of parameters of the same type into a method; the method will treat the parameters as a single array.Arrays can contain more than one dimension. A two-dimensional array has two indexes, which you can think of as rows and columns.
A rectangular array is a two-dimensional array in which all the rows have the same number of columns.
A jagged array is an array of arrays—the rows do not need to be all the same length.
The
Lengthproperty of an array returns the total number of elements in the array.The array class contains a number of methods for searching, sorting, and manipulating the elements.
Although arrays may seem like a ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access