C# Tutorial - 07 - Arrays

Uploaded by ProgrammingVideos on 14.01.2010

Arrays are data structures used for storing collections of values. To declare an array
we append a set of square brackets to the data type we want the array to contain. They
can be declared with any data type and all of its elements must then be of that type.
We allocate the array using the new keyword, followed by the data type again, and another
set of square brackets containing the length of the array. This is the fixed number of
elements that the array can contain. Once the array is created the elements will automatically
be assigned to the default values for that data type.
To fill the elements we can reference them one at a time, by placing the element's index
inside the square brackets, and then assigning them values. Notice that the index starts
with zero. We can also assign the values all at once using a curly bracket notation. The
new keyword and data type can also be left out since the compiler already knows what
we want to do. Once the array elements are initialized we access them simply by referencing
the index of the element we want inside of the square brackets.
There are also two kinds of multi-dimensional arrays in C# - rectangular and jagged. A rectangular
array has the same length of all sub-arrays and separates the dimensions using a comma.
As with single-dimensional arrays they can either be filled in one at a time or all at
once during the allocation.
Next we have jagged arrays which are arrays of arrays and can therefore have irregular
dimensions. Since we only allocate them one dimensions at a time the sub-arrays can be
allocated to different sizes and then assigned values. It's also possible to assign the values
during the allocation.
These are all examples of two dimensional arrays. If we want more than two dimensions
we can add more commas for rectangular arrays or more square brackets for jagged arrays.