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.


In C#, you need to declare arrays as type[] name ; the optional C++-style declaration type name[]; isn't available in C#.

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. 


Note that the first element in the command-line argument array holds the first argument passed to the program in C#, not the name of the program as in C++.

Microsoft Visual C#. NET 2003 Kick Start
Microsoft Visual C#.NET 2003 Kick Start
ISBN: 0672325470
EAN: 2147483647
Year: 2002
Pages: 181

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: