Previous Page
Next Page

Chapter 10 Quick Reference

To

Do this

Declare an array variable

Write the name of the element type, followed by square brackets, followed by the name of the variable, followed by a semicolon. For example:

bool[] flags;

Create an instance of an array

Write the keyword new, followed by the name of the element type, followed by the size of the array between square brackets. For example:

bool[] flags = new bool[10];

Initialize the elements of an array instance to specific values

Write the specific values in a comma-separated list between curly brackets. For example:

bool[] flags = { true, false, true, false };

Find the number of elements in an array

Use the Length property. For example:

int noOfElements = flags.Length;

Access a single array element

Write the name of the array variable, followed by the integer index of the element between square brackets. Remember, array indexing starts at zero, not one. For example:

bool initialElement = flags[0 ];

Iterate through the elements of an array or collection

Use a for statement or a foreach statement. For example:

bool[] flags = { true, false, true, false }; 
for (int i = 0; i != flags.Length; i++) 
{ 
    Console.WriteLine(flags[i ]); 
} 
 
foreach (bool flag in flags) 
{ 
    Console.WriteLine(flag); 
}

Find the number of elements in a collection

Use the Count property. For example:

int noOfElements = flags.Count;

Previous Page
Next Page