Chapter 12. Arrays


Arrays in C# is a more complex topic than in Java. Java has only one category of multi-dimensional array. C# groups multi-dimensional arrays into two distinct categories: 'normal' rectangular arrays, and jagged arrays (see Figure 12.1). Things can be a bit confusing because you can view a Java multi-dimensional array as in either category, though I personally think that it fits a little better into 'rectangular arrays'.

Figure 12.1. The different types of arrays in C#.

graphics/12fig01.gif

We will start with the simplest, one dimensional (1D) arrays. Then rectangular multi-dimensional arrays will be covered followed by the more complex jagged multi-dimensional arrays. I shall limit my discussion to 2D arrays for the sections on multi-dimensional arrays “ you can extend the idea to n -levels once you have understood the discussion. This chapter ends with some suggestions on how rectangular and jagged arrays can be used together.

I will discuss some general characteristics of arrays in C# first.

Like Java

  • Arrays are objects in C#. All arrays are subclasses of System.Array in C#. [1]

    [1] In Java, array objects are direct subclasses of java.lang.Object .

  • An array's index starts from 0.

  • You cannot access beyond the allocated size of an array. If a 1D array has been declared with a size of 6, attempting to access the array through ArrayName[6] or ArrayName[-1] will cause a runtime exception to be thrown. [2]

    [2] The exception thrown in System.IndexArrayOutOfRangeException “ the equivalent of Java's java.lang.ArrayIndexOutOfBoundsException . Accessing beyond an array's range is allowed in C/C++, where the array boundaries are not checked during runtime.

Unlike Java

  • The syntax for declaring arrays is different in C#. This will be elaborated on in the next few sections.

  • Be careful here “ the Length property of an array in C# gives the total size of an array. For a multi-dimensional array, it gives the total size of the whole array, instead of just the size of the ' first-level array'. An example will be provided to illustrate this in section 12.2.

Additional note

C# comes with a new useful looping keyword, foreach , which is very convenient for looping through an array (see section 11.1).



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net