Initializing Array Elements in Place


C# offers a syntax by which you can create an array and initialize the items in place without having to navigate through all the items in the array.

To initialize an array in place:

  1. Create an array of either valuetypes or reference types, for example: int[] nums = new int[] (without specifying a dimension).

  2. Before the semicolon to end the statement, type an open curly bracket { .

  3. Type the values for each element in the array separated by commas, for example: 5,4,6,3,1 . The number of elements will dictate the dimension of the array.

  4. Type a close curly bracket } .

  5. Type a semicolon ; ( Figure 9.22 ).

    Figure 9.22 This notation makes it easy to create an array and initialize it in place.
     void Task() {    int[] totallyRandomNums = new int[]  { 1,45,-35,42 }  ; } 

graphics/tick.gif Tips

  • You can also use this technique with reference types ( Figure 9.23 ).

    Figure 9.23 When you initialize arrays of reference types, you can create the objects in place inside the curly brackets or create them beforehand and put the variables that store the objects in curly brackets.
     class Fruit {    public string Name;    public bool HasSeeds;    public Fruit(string name,    bool hasSeeds)    {       Name = name;       HasSeeds = hasSeeds;    } } void Task() {    Fruit[] salad = new Fruit[]    {  new Fruit("Banana",false),   new Fruit("Apples",true),   new Fruit("Watermelon",true)  } } 
  • This technique also is convenient for creating an array on the fly to send to a function without having to first declare the array and store it in a variable ( Figure 9.24 ).

    Figure 9.24 This is a common situation. You have several objects in individual variables. Then you need to make a call to a function like TransferMoney that has an array parameter. You can use the curly bracket notation to create an array for the one method call and then discard it.
     class Account {    public double Balance; } void TransferMoney(Account[] accts) { } void Task() {    Account acct1 = new Account();    acct1.Balance = 45.0;    Account acct2 = new Account();    acct2.Balance = -3.0;  TransferMoney(new Account[] {acct1, acct2} );  } 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net