int[] numbers; // declare numbers as an int array of any size
numbers = new int[10]; // numbers is a 10-element array
numbers = new int[20]; // now it's a 20-element array
Single-dimensional arrays:
int[] numbers;
Multidimensional arrays:
string[,] names;
Array-of-arrays (jagged):
byte[][] scores;
Single-dimensional arrays:
int[] numbers = new int[5];
Multidimensional arrays:
string[,] names = new string[5,4];
Array-of-arrays (jagged):
byte[][] scores = new byte[5][];
for (int x = 0; x < scores.Length; x++)
{
scores[x] = new byte[4];
}
You can also have larger arrays. For example, you can have a three-dimensional rectangular array:
int[,,] buttons = new int[4,5,3];
Example
The following is a complete C# program that declares and instantiates arrays as discussed above.
// arrays.cs
using System;
class DeclareArraysSample
{
public static void Main()
{
// Single-dimensional array
int[] numbers = new int[5];
// Multidimensional array
string[,] names = new string[5,4];
// Array-of-arrays (jagged array)
byte[][] scores = new byte[5][];
// Create the jagged array
for (int i = 0; i < scores.Length; i++)
{
scores[i] = new byte[i+3];
}
// Print length of each row
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine("Length of row {0} is {1}", i, scores[i].Length);
}
}
}
Output
Length of row 0 is 3
Length of row 1 is 4
Length of row 2 is 5
Length of row 3 is 6
Length of row 4 is 7