3.8.The Array Type

Another data type is the Array, which can be thought of as a container that has a list of storage locations for a specified type. When declaring an Array, specify the type, name, dimensions, and size.

Listing 2-4. Array Operations: Array.cs

using System;

class Array
{
publicstaticvoid Main()
{
int[] myInts = { 5, 10, 15 };
bool[][] myBools = newbool[2][];
myBools[0] = newbool[2];
myBools[1] = newbool[1];
double[,] myDoubles = newdouble[2, 2];
string[] myStrings = newstring[3];

Console.WriteLine(“myInts[0]: {0}, myInts[1]: {1}, myInts[2]: {2}”, myInts[0], myInts[1], myInts[2]);

myBools[0][0] = true;
myBools[0][1] = false;
myBools[1][0] = true;
Console.WriteLine(“myBools[0][0]: {0}, myBools[1][0]: {1}”, myBools[0][0], myBools[1][0]);

myDoubles[0, 0] = 3.147;
myDoubles[0, 1] = 7.157;
myDoubles[1, 1] = 2.117;
myDoubles[1, 0] = 56.00138917;
Console.WriteLine(“myDoubles[0, 0]: {0}, myDoubles[1, 0]: {1}”, myDoubles[0, 0], myDoubles[1, 0]);

myStrings[0] = “Joe”;
myStrings[1] = “Matt”;
myStrings[2] = “Robert”;
Console.WriteLine(“myStrings[0]: {0}, myStrings[1]: {1}, myStrings[2]: {2}”, myStrings[0], myStrings[1], myStrings[2]);

}
}

And here’s the output:

myInts[0]: 5, myInts[1]: 10, myInts[2]: 15myBools[0][0]: true, myBools[1][0]: truemyDoubles[0, 0]: 3.147, myDoubles[1, 0]: 56.00138917myStrings[0]: Joe, myStrings[1]: Matt, myStrings[2]: Robert

Listing 2-4 shows different implementations of Arrays. The first example is the myInts Array, which is a single-dimension array. It is initialized at declaration time with explicit values.

Next is a jagged array, myBools. It is essentially an array of arrays. We needed to use the new operator to instantiate the size of the primary array and then use the new operator again for each sub-array.

The third example is a two dimensional array, myDoubles. Arrays can be multi-dimensional, with each dimension separated by a comma. It must also be instantiated with the new operator.

One of the differences between jagged arrays, myBools[][], and multi-dimension arrays, myDoubles[,], is that a multi-dimension array will allocate memory for every element of each dimension, whereas a jagged array will only allocate memory for the size of each array in each dimension that you define. Most of the time, you’ll be using multi-dimension arrays, if you need multiple dimensions, and will only use jagged arrays in very special circumstances when you are able to save significant memory by explicitly specifying the sizes of the arrays in each dimension.

Finally, we have the single-dimensional array of string types, myStrings.

In each case, you can see that array elements are accessed by identifying the integer index for the item you wish to refer to. Arrays sizes can be any int type value. Their indexes begin at 0.

Yes No Suggest edit
Suggest Edit