Free mag vol1 | Page 198

CHAPTER 4  CORE C# PROGRAMMING CONSTRUCTS, PART II Understanding C# Arrays As I would guess you are already aware, an array is a set of data items, accessed using a numerical index. More specifically, an array is a set of contiguous data points of the same type (an array of ints, an array of strings, an array of SportsCars, and so on). Declaring, filling, and accessing an array with C# is quite straightforward. To illustrate, create a new Console Application project (named FunWithArrays) that contains a helper method named SimpleArrays(), invoked from within Main(): class Program { static void Main(string[] args) { Console.WriteLine("***** Fun with Arrays *****"); SimpleArrays(); Console.ReadLine(); } static void SimpleArrays() { Console.WriteLine("=> Simple Array Creation."); // Create an array of ints containing 3 elements indexed 0, 1, 2 int[] myInts = new int[3]; } } // Create a 100 item string array, indexed 0 - 99 string[] booksOnDotNet = new string[100]; Console.WriteLine(); Look closely at the previous code comments. When declaring a C# array using this syntax, the number used in the array declaration represents the total number of items, not the upper bound. Also note that the lower bound of an array always begins at 0. Thus, when you write int[] myInts = new int[3], you end up with an array holding three elements, indexed at positions 0, 1, 2. After you have defined an array variable, you are then able to fill the elements index by index as shown in the updated SimpleArrays() method: static void SimpleArrays() { Console.WriteLine("=> Simple Array Creation."); // Create and fill an array of 3 Integers int[] myInts = new int[3]; myInts[0] = 100; myInts[1] = 200; myInts[2] = 300; } // Now print each value. foreach(int i in myInts) Console.WriteLine(i); Console.WriteLine(); 133