- 1 A First C# Program
- 2 Namespaces
- 3 Alternative Forms of the Main() Function
- 4 Making a Statement
- 5 Opening a Text File for Reading and Writing
- 6 Formatting Output
- 7 The string Type
- 8 Local Objects
- 9 Value and Reference Types
- 10 The C# Array
- 11 The new Expression
- 12 Garbage Collection
- 13 Dynamic Arrays: The ArrayList Collection Class
- 14 The Unified Type System
- 15 Jagged Arrays
- 16 The Hashtable Container
- 17 Exception Handling
- 18 A Basic Language Handbook for C#
1.10 The C# Array
The built-in array in C# is a fixed-size container holding elements of a single type. When we declare an array object, however, the actual size of the array is not part of its declaration. In fact, providing an explicit size generates a compile-time errorfor example,
string [] text; // OK string [ 10 ] text; // error
We declare a multidimensional array by marking each additional dimension with a comma, as follows:
string [,] two_dimensions; string [,,] three_dimensions; string [,,,] four_dimensions;
When we write
string [] messages;
messages represents a handle to an array object of string elements, but it is not itself the array object. By default, messages is set to null. Before we can store elements within the array, we have to create the array object using the new expression. This is where we indicate the size of the array:
messages = new string[ 4 ];
messages now refers to an array of four string elements, accessed through index 0 for the first element, 1 for the second, and so on:
messages[ 0 ] = "Hi. Please enter your name: "; messages[ 1 ] = "Oops. Invalid name. Please try again: "; // ... messages[ 3 ] = "Well, that's enough. Bailing out!";
An attempt to access an undefined element, such as the following indexing of an undefined fifth element for our messages array:
messages[ 4 ] = "Well, OK: one more try";;
results in a runtime exception being thrown rather than a compile-time error:
Exception occurred: System.IndexOutOfRangeException: An exception of type System.IndexOutOfRangeException was thrown.