15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

130 ❘ ChaPTer 6 ArrAys And tuples<br />

array initialization<br />

After declaring an array, memory must be allocated to hold all the elements of the array. An array is a<br />

reference type, so memory on the heap must be allocated. You do this by initializing the variable of the<br />

array using the new operator with the type <strong>and</strong> the number of elements inside the array. Here you specify the<br />

size of the array:<br />

myArray = new int[4];<br />

Value <strong>and</strong> reference types are covered in Chapter 3, “ Objects <strong>and</strong> Types .”<br />

With this declaration <strong>and</strong> initialization, the variable myArray references four integer values that are<br />

allocated on the managed heap (see Figure 6 - 1).<br />

Stack<br />

myArray<br />

Managed Heap<br />

int<br />

int<br />

int<br />

int<br />

figure 6-1<br />

The array cannot be resized after the size was specifi ed without copying all elements. If<br />

you don ’ t know the number of elements that should be in the array in advance, you can<br />

use a collection (see Chapter 10).<br />

Instead of using a separate line to declare <strong>and</strong> initialize an array, you can use a single line:<br />

int[] myArray = new int[4];<br />

You can also assign values to every array element using an array initializer. Array initializers can be<br />

used only while declaring an array variable, not after the array is declared:<br />

int[] myArray = new int[] {4, 7, 11, 2};<br />

If you initialize the array using curly brackets, the size of the array can also be left out, because the<br />

compiler can count the number of elements itself:<br />

int[] myArray = new int[] {4, 7, 11, 2};<br />

There ’ s even a shorter form using the <strong>C#</strong> compiler. Using curly brackets you can write the<br />

array declaration <strong>and</strong> initialization. The code generated from the compiler is the same as in the<br />

previous example:<br />

int[] myArray = {4, 7, 11, 2};<br />

accessing array elements<br />

After an array is declared <strong>and</strong> initialized, you can access the array elements using an indexer. Arrays<br />

only support indexers that have integer parameters.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!