- Arrays
- Types of Arrays
- An Array as an Object
- One-Dimensional and Rectangular Arrays
- Instantiating a One-Dimensional or Rectangular Array
- Accessing Array Elements
- Initializing an Array
- Jagged Arrays
- Comparing Rectangular and Jagged Arrays
- The foreach Statement
- Array Covariance
- Useful Inherited Array Members
- Comparing Array Types
An array is a set of uniform data elements represented by a single variable name. The individual elements are accessed using the variable name together with one or more indexes between square brackets, as shown here:
Array name Index
↓ ↓
MyArray[4]
Let's start with some important definitions having to do with arrays in C#.
The following are some important general facts about C# arrays:
C# provides two kinds of arrays:
Additionally, there are two types of multidimensional arrays: rectangular arrays and jagged arrays; they have the following characteristics:
int x = myArray2[4, 6, 1] // One set of square brackets
jagArray1[2][7][4] // Three sets of square brackets
Figure 12-2 shows the kinds of arrays available in C#.
An array instance is an object whose type derives from class System.Array
. Since arrays are derived from this BCL base class, they inherit a number of useful members from it, such as the following:
Rank
: A property that returns the number of dimensions of the arrayLength
: A property that returns the length (the total number of elements) of the arrayArrays are reference types, and as with all reference types, they have both a reference to the data and the data object itself. The reference is either on the stack or in the heap, and the data object itself is always in the heap. Figure 12-3 shows the memory configuration and components of an array.
Although an array is always a reference type, the elements of the array can be either value types or reference types.
Figure 12-4 shows a value type array and a reference type array.
Syntactically, one-dimensional arrays and rectangular arrays are very similar, so I'll treat them together. I'll then treat jagged arrays separately.
To declare a one-dimensional or rectangular array, use a single set of square brackets between the type and the variable name.
The rank specifiers are commas between the brackets. They specify the number of dimensions the array will have. The rank is the number of commas, plus one. For example, no commas indicates a one-dimensional array, one comma indicates a two-dimensional array, and so forth.
The base type, together with the rank specifiers, is the type of the array. For example, the following line of code declares a one-dimensional array of long
s. The type of the array is long[]
, which is read as “an array of longs.”
Rank specifiers = 1
↓
long[ ] secondArray;
↑
Array type
The following code shows examples of declarations of rectangular arrays. Notice the following:
Rank specifiers
↓
int[,,] firstArray; // Array type: 3D array of int
int[,] arr1; // Array type: 2D array of int
long[,,] arr3; // Array type: 3D array of long
↑
Array type
long[3,2,6] SecondArray; // Wrong! Compile error
↑ ↑ ↑
Dimension lengths not allowed!
Note Unlike in C/C++, in C# the brackets follow the base type, not the variable name.
To instantiate an array, you use an array-creation expression. An array-creation expression consists of the new
operator, followed by the base type, followed by a pair of square brackets. The length of each dimension is placed in a comma-separated list between the brackets.
The following are examples of one-dimensional array declarations.
arr2
is a one-dimensional array of four int
s.mcArr
is a one-dimensional array of four MyClass
references.Figure 12-5 shows their layouts in memory.
Four elements
↓
int[] arr2 = new int[4];
MyClass[] mcArr = new MyClass[4];
↑
Array-creation expression
The following is an example of a rectangular array.
arr3
is a three-dimensional array.Figure 12-5 shows its layout in memory.
Lengths of the dimensions
↓
int[,,] arr3 = new int[3,6,2] ;
Note Unlike object-creation expressions, array-creation expressions do not contain parentheses—even for reference type arrays.
An array element is accessed using an integer value as an index into the array.
The following code shows examples of declaring, writing to, and reading from a one-dimensional and a two-dimensional array:
int[] intArr1 = new int[15]; // Declare 1D array of 15 elements.
intArr1[2] = 10; // Write to element 2 of the array.
int var1 = intArr1[2]; // Read from element 2 of the array.
int[,] intArr2 = new int[5,10]; // Declare 2D array.
intArr2[2,3] = 7; // Write to the array.
int var2 = intArr2[2,3]; // Read from the array.
The following code shows the full process of creating and accessing a one-dimensional array:
int[] myIntArray; // Declare the array.
myIntArray = new int[4]; // Instantiate the array.
for( int i=0; i<4; i++ ) // Set the values.
myIntArray[i] = i*10;
// Read and display the values of each element.
for( int i=0; i<4; i++ )
Console.WriteLine("Value of element {0} = {1}", i, myIntArray[i]);
This code produces the following output:
Value of element 0 is 0
Value of element 1 is 10
Value of element 2 is 20
Value of element 3 is 30
Whenever an array is created, each of the elements is automatically initialized to the default value for the type. The default values for the predefined types are 0
for integer types, 0.0
for floating-point types, false
for Booleans, and null
for reference types.
For example, the following code creates an array and initializes its four elements to the value 0
. Figure 12-6 illustrates the layout in memory.
int[] intArr = new int[4];
For a one-dimensional array, you can set explicit initial values by including an initialization list immediately after the array-creation expression of an array instantiation.
For example, the following code creates an array and initializes its four elements to the values between the curly braces. Figure 12-7 illustrates the layout in memory.
Initialization list
↓
int[] intArr = new int[] { 10, 20, 30, 40 };
↑
No connecting operator
To explicitly initialize a rectangular array, you need to follow these rules:
For example, the following code shows the declaration of a two-dimensional array with an initialization list. Figure 12-8 illustrates the layout in memory.
Initialization lists separated by commas
↓ ↓
int[,] intArray2 = new int[,] { {10, 1}, {2, 10}, {11, 9} } ;
Rectangular arrays are initialized with nested, comma-separated initialization lists. The initialization lists are nested in curly braces. This can sometimes be confusing, so to get the nesting, grouping, and commas right, consider the following tips:
For example, read the following declaration as “intArray
has four groups of three groups of two elements.”
Initialization lists, nested and separated by commas
int[,,] intArray = new int[4,3,2] { ↓ ↓ ↓
{ {8, 6}, {5, 2}, {12, 9} },
{ {6, 4}, {13, 9}, {18, 4} },
{ {7, 2}, {1, 13}, {9, 3} },
{ {4, 6}, {3, 2}, {23, 8} }
};
When combining declaration, array creation, and initialization in a single statement, you can omit the array-creation expression part of the syntax entirely and provide just the initialization portion. Figure 12-9 shows this shortcut syntax.
So far, we've explicitly specified the array types at the beginnings of all our array declarations. But, like other local variables, your local arrays can also be implicitly typed. This means the following:
var
instead of the array type.The following code shows explicit and implicit versions of three array declarations. The first set is a one-dimensional array of int
s. The second is a two-dimensional array of int
s. The third is an array of strings. Notice that in the declaration of implicitly typed intArr4
you still need to include the rank specifier in the initialization.
Explicit Explicit
↓ ↓
int [] intArr1 = new int[] { 10, 20, 30, 40 };
var intArr2 = new [] { 10, 20, 30, 40 };
↑ ↑
Keyword Inferred
int[,] intArr3 = new int[,] { { 10, 1 }, { 2, 10 }, { 11, 9 } };
var intArr4 = new [,] { { 10, 1 }, { 2, 10 }, { 11, 9 } };
↑
Rank specifier
string[] sArr1 = new string[] { "life", "liberty", "pursuit of happiness" };
var sArr2 = new [] { "life", "liberty", "pursuit of happiness" };
The following code puts together all the pieces we've looked at so far. It creates, initializes, and uses a rectangular array.
// Declare, create, and initialize an implicitly typed array.
var arr = new int[,] {{0, 1, 2}, {10, 11, 12}};
// Print the values.
for( int i=0; i<2; i++ )
for( int j=0; j<3; j++ )
Console.WriteLine("Element [{0},{1}] is {2}", i, j, arr[i,j]);
This code produces the following output:
Element [0,0] is 0
Element [0,1] is 1
Element [0,2] is 2
Element [1,0] is 10
Element [1,1] is 11
Element [1,2] is 12
A jagged array is an array of arrays. Unlike rectangular arrays, the subarrays of a jagged array can have different numbers of elements.
For example, the code below declares a two-dimensional jagged array. Figure 12-10 shows the array's layout in memory.
jagArr
is an array of three arrays of int
s.”int[][] jagArr = new int[3][]; // Declare and create top-level array.
... // Declare and create subarrays.
The declaration syntax for jagged arrays requires a separate set of square brackets for each dimension. The number of sets of square brackets in the declaration of the array variable determines the rank of the array.
Rank specifiers
↓
int[][] SomeArr; // Rank = 2
int[][][] OtherArr; // Rank = 3
↑ ↑
Array type Array name
You can combine the jagged array declaration with the creation of the first-level array using an array-creation expression, such as in the following declaration. Figure 12-11 shows the result.
Three subarrays
↓
int[][] jagArr = new int[3][];
You cannot instantiate more than the first-level array in the declaration statement.
Allowed
↓
int[][] jagArr = new int[3][4]; // Wrong! Compile error
↑
Not allowed
Unlike other types of arrays, you cannot fully instantiate a jagged array in a single step. Since a jagged array is an array of independent arrays, each array must be created separately. Instantiating a full jagged array requires the following steps:
For example, the following code shows the declaration, instantiation, and initialization of a two-dimensional jagged array. Notice in the code that the reference to each subarray is assigned to an element in the top-level array. Steps 1 through 4 in the code correspond to the numbered representations in Figure 12-12.
int[][] Arr = new int[3][]; // 1. Instantiate top level.
Arr[0] = new int[] {10, 20, 30}; // 2. Instantiate subarray.
Arr[1] = new int[] {40, 50, 60, 70}; // 3. Instantiate subarray.
Arr[2] = new int[] {80, 90, 100, 110, 120}; // 4. Instantiate subarray.
Since the subarrays in a jagged array are themselves arrays, it's possible to have rectangular arrays inside jagged arrays. For example, the following code creates a jagged array of three two-dimensional rectangular arrays and initializes them with values. It then displays the values. Figure 12-13 illustrates the structure.
The code uses the GetLength(int n)
method of arrays, inherited from System.Array
, to get the length of the specified dimension of the array.
int[][,] Arr; // An array of 2D arrays
Arr = new int[3][,]; // Instantiate an array of three 2D arrays.
Arr[0] = new int[,] { { 10, 20 },
{ 100, 200 } };
Arr[1] = new int[,] { { 30, 40, 50 },
{ 300, 400, 500 } };
Arr[2] = new int[,] { { 60, 70, 80, 90 },
{ 600, 700, 800, 900 } };
↓ Get length of dimension 0 of Arr.
for (int i = 0; i < Arr.GetLength(0); i++)
{
↓ Get length of dimension 0 of Arr[ i ].
for (int j = 0; j < Arr[i].GetLength(0); j++)
{
↓ Get length of dimension 1 of Arr[ i ].
for (int k = 0; k < Arr[i].GetLength(1); k++)
{
Console.WriteLine
("[{0}][{1},{2}] = {3}", i, j, k, Arr[i][j, k]);
}
Console.WriteLine("");
}
Console.WriteLine("");
}
This code produces the following output:
[0][1,0] = 100
[0][1,1] = 200
[1][0,0] = 30
[1][0,1] = 40
[1][0,2] = 50
[1][1,0] = 300
[1][1,1] = 400
[1][1,2] = 500
[2][0,0] = 60
[2][0,1] = 70
[2][0,2] = 80
[2][0,3] = 90
[2][1,0] = 600
[2][1,1] = 700
[2][1,2] = 800
[2][1,3] = 900
The structure of rectangular and jagged arrays is significantly different. For example, Figure 12-14 shows the structure of a rectangular three-by-three array, as well as a jagged array of three one-dimensional arrays of length 3.
One-dimensional arrays have specific instructions in the CIL that allow them to be optimized for performance. Rectangular arrays do not have these instructions and are not optimized to the same level. Because of this, it can sometimes be more efficient to use jagged arrays of one-dimensional arrays—which can be optimized—than rectangular arrays, which cannot.
On the other hand, the programming complexity can be significantly less for a rectangular array because it can be treated as a single unit, rather than an array of arrays.
The foreach
statement allows you to sequentially access each element in an array. It's actually a more general construct in that it also works with other collection types as well—but in this section I'll only discuss its use with arrays. Chapter 18 covers its use with other collection types.
The important points of the foreach
statement are the following:
foreach
statement uses the iteration variable to sequentially represent each element in the array.foreach
statement is shown below, where
Type
is the type of the elements of the array. You can explicitly supply its type, or you can use var
and let it be implicitly typed and inferred by the compiler, since the compiler knows the type of the array.Identifier
is the name of the iteration variable.ArrayName
is the name of the array to be iterated through.Statement
is a simple statement or a block that is executed once for each element in the array. Explicitly typed iteration variable declaration
↓
foreach( Type Identifier in ArrayName )
Statement
Implicitly typed iteration variable declaration
↓
foreach( var Identifier in ArrayName )
Statement
In the following text, I'll sometimes use implicit typing, and other times I'll use explicit typing so that you can see the exact type being used. But the forms are semantically equivalent.
The foreach
statement works in the following way:
foreach
statement selects the next element in the array and repeats the process.In this way, it cycles through the array, allowing you to access each element one by one. For example, the following code shows the use of a foreach
statement with a one-dimensional array of four integers:
WriteLine
statement, which is the body of the foreach
statement, is executed once for each of the elements of the array.item
has the value of the first element of the array. Each successive time, it has the value of the next element in the array. int[] arr1 = {10, 11, 12, 13};
Iteration variable declaration
↓ Iteration variable use
foreach( int item in arr1 ) ↓
Console.WriteLine("Item Value: {0}", item);
This code produces the following output:
Item Value: 10
Item Value: 11
Item Value: 12
Item Value: 13
Since the value of the iteration variable is read-only, clearly it cannot be changed. But this has different effects on value type arrays and reference type arrays.
For value type arrays, this means you cannot change an element of the array when it's being represented by the iteration variable. For example, in the following code, the attempt to change the data in the iteration variable produces a compile-time error message:
int[] arr1 = {10, 11, 12, 13};
foreach( int item in arr1 )
item++; // Compilation error. Changing variable value is not allowed.
For reference type arrays, you still cannot change the iteration variable, but the iteration variable only holds the reference to the data, not the data itself. So although you cannot change the reference, you can change the data through the iteration variable.
The following code creates an array of four MyClass
objects and initializes them. In the first foreach
statement, the data in each of the objects is changed. In the second foreach
statement, the changed data is read from the objects.
class MyClass
{
public int MyField = 0;
}
class Program
{
static void Main()
{
MyClass[] mcArray = new MyClass[4]; // Create array.
for (int i = 0; i < 4; i++)
{
mcArray[i] = new MyClass(); // Create class objects.
mcArray[i].MyField = i; // Set field.
}
foreach (MyClass item in mcArray)
item.MyField += 10; // Change the data.
foreach (MyClass item in mcArray)
Console.WriteLine("{0}", item.MyField); // Read the changed data.
}
}
This code produces the following output:
10
11
12
13
In a multidimensional array, the elements are processed in the order in which the rightmost index is incremented fastest. When the index has gone from 0 to length – 1, the next index to the left is incremented, and the indexes to the right are reset to 0.
The following example shows the foreach
statement used with a rectangular array:
class Program
{
static void Main()
{
int total = 0;
int[,] arr1 = { {10, 11}, {12, 13} };
foreach( var element in arr1 )
{
total += element;
Console.WriteLine
("Element: {0}, Current Total: {1}", element, total);
}
}
}
This code produces the following output:
Element: 10, Current Total: 10
Element: 11, Current Total: 21
Element: 12, Current Total: 33
Element: 13, Current Total: 46
Since jagged arrays are arrays of arrays, you must use separate foreach
statements for each dimension in the jagged array. The foreach
statements must be nested properly to make sure that each nested array is processed properly.
For example, in the following code, the first foreach
statement cycles through the top-level array—arr1
—selecting the next subarray to process. The inner foreach
statement processes the elements of that subarray.
class Program
{
static void Main( )
{
int total = 0;
int[][] arr1 = new int[2][];
arr1[0] = new int[] { 10, 11 };
arr1[1] = new int[] { 12, 13, 14 };
foreach (int[] array in arr1) // Process the top level.
{
Console.WriteLine("Starting new array");
foreach (int item in array) // Process the second level.
{
total += item;
Console.WriteLine(" Item: {0}, Current Total: {1}", item, total);
}
}
}
}
This code produces the following output:
Starting new array
Item: 10, Current Total: 10
Item: 11, Current Total: 21
Starting new array
Item: 12, Current Total: 33
Item: 13, Current Total: 46
Item: 14, Current Total: 60
Under certain conditions, you can assign an object to an array element even if the object is not of the array's base type. This property of arrays is called array covariance. You can use array covariance if the following are true:
Since there is always an implicit conversion between a derived class and its base class, you can always assign an object of a derived class to an array declared for the base class.
For example, the following code declares two classes, A
and B
, where class B
derives from class A
. The last line shows covariance by assigning objects of type B
to array elements of type A
. Figure 12-15 shows the memory layout for the code.
class A { ... } // Base class
class B : A { ... } // Derived class
class Program {
static void Main() {
// Two arrays of type A[]
A[] AArray1 = new A[3];
A[] AArray2 = new A[3];
// Normal--assigning objects of type A to an array of type A
AArray1[0] = new A(); AArray1[1] = new A(); AArray1[2] = new A();
// Covariant--assigning objects of type B to an array of type A
AArray2[0] = new B(); AArray2[1] = new B(); AArray2[2] = new B();
}
}
Note There is no covariance for value type arrays.
I mentioned earlier that C# arrays are derived from class System.Array
. From that base class they inherit a number of useful properties and methods. Table 12-1 lists some of the most useful ones.
For example, the following code uses some of these properties and methods:
public static void PrintArray(int[] a)
{
foreach (var x in a)
Console.Write("{0} ", x);
Console.WriteLine("");
}
static void Main()
{
int[] arr = new int[] { 15, 20, 5, 25, 10 };
PrintArray(arr);
Array.Sort(arr);
PrintArray(arr);
Array.Reverse(arr);
PrintArray(arr);
Console.WriteLine();
Console.WriteLine("Rank = {0}, Length = {1}",arr.Rank, arr.Length);
Console.WriteLine("GetLength(0) = {0}",arr.GetLength(0));
Console.WriteLine("GetType() = {0}",arr.GetType());
}
This code produces the following output:
15 20 5 25 10
5 10 15 20 25
25 20 15 10 5
Rank = 1, Length = 5
GetLength(0) = 5
GetType() = System.Int32[]
The Clone
method performs a shallow copy of an array. This means that it only creates a clone of the array itself. If it is a reference type array, it does not copy the objects referenced by the elements. This has different results for value type arrays and reference type arrays.
The Clone
method returns a reference of type object
, which must be cast to the array type.
int[] intArr1 = { 1, 2, 3 };
Array type Returns an object
↓ ↓
int[] intArr2 = ( int[] ) intArr1.Clone();
For example, the following code shows an example of cloning a value type array, producing two independent arrays. Figure 12-16 illustrates the steps shown in the code.
static void Main()
{
int[] intArr1 = { 1, 2, 3 }; // Step 1
int[] intArr2 = (int[]) intArr1.Clone(); // Step 2
intArr2[0] = 100; intArr2[1] = 200; intArr2[2] = 300; // Step 3
}
Cloning a reference type array results in two arrays pointing at the same objects. The following code shows an example. Figure 12-17 illustrates the steps shown in the code.
class A
{
public int Value = 5;
}
class Program
{
static void Main()
{
A[] AArray1 = new A[3] { new A(), new A(), new A() }; // Step 1
A[] AArray2 = (A[]) AArray1.Clone(); // Step 2
AArray2[0].Value = 100;
AArray2[1].Value = 200;
AArray2[2].Value = 300; // Step 3
}
}
Table 12-2 summarizes some of the important similarities and differences between the three types of arrays.
18.118.12.186