X hits on this document

886 views

0 shares

0 downloads

0 comments

40 / 396

Chapter ‎18   Unsafe code

The following example creates an array of int elements, initializes the array, and prints out the contents of the array.

using System;

class Test { static void Main() { int[] a = new int[10]; for (int i = 0; i < a.Length; i++) a[i] = i * i; for (int i = 0; i < a.Length; i++) { Console.WriteLine("a[{0}] = {1}", i, a[i]); } } }

This example creates and operates on a single-dimensional array. C# also supports multi-dimensional arrays. The number of dimensions of an array type, also known as the rank of the array type, is one plus the number of commas written between the square brackets of the array type. The following example allocates a one-dimensional, a two-dimensional, and a three-dimensional array.

int[] a1 = new int[10]; int[,] a2 = new int[10, 5]; int[,,] a3 = new int[10, 5, 2];

The a1 array contains 10 elements, the a2 array contains 50 (10 × 5) elements, and the a3 array contains 100 (10 × 5 × 2) elements.

The element type of an array can be any type, including an array type. An array with elements of an array type is sometimes called a jagged array because the lengths of the element arrays do not all have to be the same. The following example allocates an array of arrays of int:

int[][] a = new int[3][]; a[0] = new int[10]; a[1] = new int[5]; a[2] = new int[20];

The first line creates an array with three elements, each of type int[] and each with an initial value of null. The subsequent lines then initialize the three elements with references to individual array instances of varying lengths.

The new operator permits the initial values of the array elements to be specified using an array initializer, which is a list of expressions written between the delimiters { and }. The following example allocates and initializes an int[] with three elements.

int[] a = new int[] {1, 2, 3};

Note that the length of the array is inferred from the number of expressions between { and }. Local variable and field declarations can be shortened further such that the array type does not have to be restated.

int[] a = {1, 2, 3};

Both of the previous examples are equivalent to the following:

int[] a = new int[3]; a[0] = 1; a[1] = 2; a[2] = 3;

1.9 Interfaces

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.27

Document info
Document views886
Page views886
Page last viewedTue Dec 06 09:04:10 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments