Using Arrays As Return Values from Methods

   


C# allows a method to return an array object reference back to the caller. Figure 10.12 shows the relevant parts of a source program making use of this feature. Two methods are defined here Main (lines 5 40) and GetTenRandomNumbers (lines 50 71). The latter will, when called, return a reference to an array containing ten random numbers. These numbers could be used for various mathematical analyses (irrelevant for this demonstration and therefore not shown) performed in the Main method.

Figure 10.12. Returning a reference to an array object of base type int.
graphics/10fig12.gif

Recall that the return type for a method is specified just prior to the method name of the method header, such as in the following:

 private static int Sum (int a, int b) 

where the method header in this case specifies Sum to return a value of type int.

By exchanging int with the array type name int [], as in the following (the method name has also changed, but this is irrelevant in this context):


graphics/10infig07.gif

of line 50, we specify the method GetTenRandomNumbers() to return a reference to an array of base type int. After GetTenRandomNumbers() has been defined, it is possible to insert its method call anyplace where a reference to array of base type int is expected. Consequently, it becomes possible to assign its return value to randomNumbers (declared in line 10), which is of a compatible type, by writing

 randomNumbers = GetTenRandomNumbers(); 

as done in line 20 of Figure 10.12. randomNumbers now references an array object with ten random numbers. Each of its array elements can be called in the usual manner as follows:

 randomNumbers[0] 

Notice that because randomArray is declared within the scope of GetTenRandomNumbers() (see line 55 of Figure 10.12), its scope is confined to this method. However, even though the new array object, whose reference is assigned to randomArray in the same line, is created within the same scope, this same array object happily lives on outside the scope of GetTenRandomNumbers() through the reference passed back to the caller (via line 70), which, in this case, resides in the Main() method.

Note

graphics/common.gif

In general, the lifetime of an array object is not determined by the scope of where it is created, but whether any references are referencing it. Consequently, array objects created inside the scope of a method can live outside the confines of this method by returning its references.


Listing 10.12 contains a fully-working program to exemplify the previous discussion. The program is similar to that of Listing 10.6, but this time the maximum individual sales of person1Sales and person2Sales (declared in lines 7 and 8) are determined via a separate method called MaxArray that assigns the maximum values to a locally created array. The reference to this array is returned from MaxArray to the Main method where it is used to print out the content of the array object and the maximum individual sales figures (see the sample output following the listing).

Listing 10.12 ReturnMaxSalesArray.cs
01: using System; 02: 03: class ReturnMaxSalesArray 04: { 05:     public static void Main() 06:     { 07:         decimal [] person1Sales = { 40000, 10000, 25000, 50000, 33000, 60000} ; 08:         decimal [] person2Sales = { 80000, 3000, 110000, 40000, 33000, 59000} ; 09:         decimal [] maxSales; 10: 11:         maxSales = MaxArray(person1Sales, person2Sales); 12:         Console.WriteLine("Max individual sales for each of the first six months: "); 13:         for (int i = 0; i < 6; i++) 14:         { 15:             Console.WriteLine("Max sales month { 0} : { 1,12:C} ", (i+1),  graphics/ccc.gifmaxSales[i]); 16:         } 17:     } 18: 19:     private static decimal [] MaxArray (decimal [] sales1, decimal [] sales2) 20:     { 21:         decimal [] maxSales = new decimal[sales1.Length]; 22: 23:         for (int i = 0; i < maxSales.Length; i++) 24:         { 25:             maxSales[i] = MaxAmount(sales1[i], sales2[i]); 26:         } 27:         return maxSales; 28:     } 29: 30:     private static decimal MaxAmount(decimal a, decimal b) 31:     { 32:         if (a > b) 33:             return a; 34:         else 35:             return b; 36:     } 37: } Max individual sales for each of the first six months: Max sales month 1:   $80,000.00 Max sales month 2:   $10,000.00 Max sales month 3:  $110,000.00 Max sales month 4:   $50,000.00 Max sales month 5:   $33,000.00 Max sales month 6:   $60,000.00 

Lines 7 9 declare three array variables. Lines 30 36 contain the method MaxAmount that is identical to MaxAmount of Listing 10.6. It returns the greater of the two arguments passed to it. Lines 19 28 contain the definition for the method MaxArray. According to the method header of line 19, it has two formal parameters sales1 and sales2 and a return value, all of type reference to an array object of base type decimal. In line 25, MaxArray compares each pair of corresponding array elements from sales1 and sales2 by applying MaxAmount. In each instance, the greatest value is assigned to the corresponding array element of the local array variable maxSales declared in line 21. After the for loop repeatedly has executed its loop body maxSales.Length times (6 in this case), the reference to the array object, created in line 21 with the new keyword and now containing the max individual sales, is returned to the caller with the return keyword in line 27.

Line 11 calls the MaxArray method and passes two arguments along, person1Sales and person2Sales. Flow of execution then moves to the beginning of the MaxArray method, where sales1 and sales2 now are referencing the same array objects as person1Sales and person2Sales, respectively. The array elements referenced by these two array variables are then processed according to MaxArray's description previously discussed. As a result, a reference to an array object containing the maximum individual sales of person1Sales and person2Sales is returned from this method call and assigned to maxSales. It is now easy, through the for loop of lines 13 16, to print out the values of this array.

Syntax Box 10.5 Method Returning an Array Object Reference

 Typical_anatomy_of_method_returning_an_array_object_reference::= public static <Base_type> [] <Method_identifier> ( <Formal_Parameter_list> graphics/ccc.gif ) {       ...       <Base_type> [] <Local_array_identifier> = new <Base_type> [<Array_length> graphics/ccc.gif];       ...       <Statements assigning values to array elements of  graphics/ccc.gif<Local_array_identifier>  >       ...       return <Local_array_identifier>; } 

Notes:

  • The method need not be declared public or static. These keywords are merely included because they are often used to declare a method.

  • The method must, like any other method, be positioned within a class or a struct definition.

Arrays and Classes

As briefly mentioned earlier, the base type of an array is not only confined to be of a primitive type, but can be any declarable type, including a class. The coming section provides examples of how to work with object references stored in array elements and the trailing section combines this ability with C#'s capability of letting arrays be instance variables in classes.


   


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

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