Using Arrays in Microsoft® Visual C#® 2013

  • 11/15/2013

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 enclosed in square brackets. For example:

bool[] flags = new bool[10];

Initialize the elements of an array to specific values

For an array, write the specific values in a comma-separated list enclosed in braces. For example:

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

Find the number of elements in an array

Use the Length property. For example:

int [] flags = ...;
...
int noOfElements = flags.Length;

Access a single array element

Write the name of the array variable, followed by the integer index of the element enclosed in square brackets. Remember, array indexing starts at 0, not 1. For example:

bool initialElement = flags[0];

Iterate through the elements of an array

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);
}

Declare a multidimensional array variable

Write the name of the element type, followed by a set of square brackets with a comma separator indicating the number of dimensions, followed by the name of the variable, followed by a semicolon. For example, use the following to create a two-dimensional array called table and initialize it to hold 4 rows of 6 columns:

int[,] table;
table = new int[4,6];

Declare a jagged array variable

Declare the variable as an array of child arrays. You can initialize each child array to have a different length. For example, use the following to create a jagged array called items and initialize each child array:

int[][] items;
items = new int[4][];
items[0] = new int[3];
items[1] = new int[10];
items[2] = new int[40];
items[3] = new int[25];