Friday, January 11, 2013

.NET Array Types

Formally speaking, an array is a collection of data points, of the same defined data type, that are accessed using a numerical index. Arrays are references types and derive from a common base class
named System.Array. By default, .NET arrays always have a lower bound of zero, although it is possible to create an array with an arbitrary lower bound using the static
System.Array.CreateInstance() method.

C# arrays can be declared in a handful of ways. First of all, if you are creating an array whose values will be specified at a later time (perhaps due to yet-to-be-obtained user input), specify the size of the array using square brackets ([]) at the time of its allocation, for example:

// Assign a string array containing 3 elements {0 - 2}
string[] booksOnCOM;
booksOnCOM = new string[3];
// Initialize a 100 item string array, numbered {0 - 99}
string[] booksOnDotNet = new string[100];

Once you have declared an array, you can make use of the indexer syntax to fill each item with a value:

// Create, populate, and print an array of three strings.

string[] booksOnCOM;
booksOnCOM = new string[3];
booksOnCOM[0] = "Developer's Workshop to COM and ATL 3.0";
booksOnCOM[1] = "Inside COM";
booksOnCOM[2] = "Inside ATL";

foreach (string s in booksOnCOM)

As a shorthand notation, if you know an array’s values at the time of declaration, you may specify these values within curly brackets. Note that in this case, the array size is optional (as it is calculated on the fly), as is the new keyword. Thus, the following declarations are identical:

// Shorthand array declaration (values must be known at time of declaration).

int[] n = new int[] { 20, 22, 23, 0 };
int[] n3 = { 20, 22, 23, 0 };

There is one final manner in which you can create an array type:

int[] n2 = new int[4] { 20, 22, 23, 0 }; // 4 elements, {0 - 3}

In this case, the numeric value specified represents the number of elements in the array, not the value of the upper bound. If there is a mismatch between the declared size and the number of initializers, you are issued a compile time error.

Regardless of how you declare an array, be aware that the elements in a .NET array are automatically
set to their respective default values until you indicate otherwise. Thus, if you have an array of numerical types, each member is set to 0 (or 0.0 in the case of floating-point numbers), objects are set
to null, and Boolean types are set to false.

No comments:
Write comments
Recommended Posts × +