Home > Articles > Programming > Windows Programming

Hello, C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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 error—for 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.
  • + Share This
  • 🔖 Save To Your Account