Just as enumerations group constants together, so arrays can be thought of as grouping variables together. There's a lot of support for arrays built into C#, and we'll take a look at it in Chapter 6. As you know, arrays store data values by index. In C#, arrays are reference types, so you can create a new array with the new operator. You declare an array as type [] , where type is the data type of each element. For example, here's how to declare an array of five integer elements: int[] array1 = new int[5]; These elements can be addressed with index values 0 to 4, as array1[0] , array1[1] , up to array1[4] . You can see this at work in Listing 1.5, where we've created a C# array, placed data in one of its elements, and displayed that data.
Listing 1.5 Using an Array (ch01_05.cs)class ch01_05 { static void Main() { int[] array1 = new int[5]; array1[0] = 1; System.Console.WriteLine("The first element holds {0}.", array1[0]); } } You can also initialize each element in an array when you declare the array by assigning it a list of values int[] array1 = {1, 2, 3, 4, 5}; array1[0] = 1; System.Console.WriteLine("The first element holds {0}.", array1[0]); One common use of arrays is for reading arguments typed on the command line when your code is invoked. If you declare an array of type string[] in the parentheses following the Main method, C# will fill that array with any command-line arguments. You can see an example in Listing 1.6, set up to take exactly four command-line arguments (any more or any less will cause an error in this example). Listing 1.6 Using an Array (ch01_06.cs)class ch01_06 { static void Main(string[] args) { System.Console.WriteLine("You entered: {0} {1} {2} {3}.", args[0], args[1], args[2], args[3]); } } Here's what you see when you run this example and type the command-line arguments "Now is the time" into this code: C:\>ch01_06 Now is the time You entered: Now is the time.
|