Home

Arrays and Methods

 

A Member of an Array as Parameter

Each member of an array is considered a sub-variable; that is, a variable in its own right with a value. Based on this, you can pass a single member of an array as argument. You can pass the name of the array variable with the accompanying index to a method.

Practical LearningPractical Learning: Passing a Member of an Array as Argument

  1. To pass members of an array to a method, access the IceCreamOrder.cs file and change it as follows:
     
    using System;
    
    namespace IceCream1
    {
        class IceCreamOrder
        {
            public const decimal BasePrice = 1.55M;
    
            public void ProcessAnOrder()
            {
                . . . No Change
    
                TotalPrice = (BasePrice * Scoops) + PriceIngredient;
    
                DisplayReceipt(Flavor[dFlv - 1], Container[dCont - 1],
                               Ingredient[dIngrd - 1], Scoops, TotalPrice);
            }
    
            public void DisplayReceipt(string Flv, string Cont, string Ingrd,
                int spoons, decimal TotalPrice)
            {
                Console.WriteLine("\n==================================");
                Console.WriteLine("Ice Cream Order");
                Console.WriteLine("----------------------------------");
                Console.WriteLine("Flavor:      {0}", Flv);
                Console.WriteLine("Container:   {0}", Cont);
                Console.WriteLine("Ingredient:  {0}", Ingrd);
                Console.WriteLine("Scoops:      {0}", spoons);
                Console.WriteLine("Total Price: {0:C}", TotalPrice);
                Console.WriteLine("==================================");
            }
        }
    }
  2. Execute the application and test it. Here is an example:
     
    Ice Cream Vendor Machine
    What type of flavor do you want?
    1 - Vanilla
    2 - Cream of Cocoa
    3 - Organic Strawberry
    4 - Butter Pecan
    5 - Cherry Coke
    6 - Chocolate Brownies
    Your Choice? 4
    What type of container do you want?
    1 - Cone
    2 - Cup
    3 - Bowl
    Your Choice? 1
    Do you want an ingredient or not
    1 - No Ingredient
    2 - Peanuts
    3 - M & M
    4 - Cookies
    Your Choice? 2
    How many scoops(1, 2, or 3)? 1
    
    ==================================
    Ice Cream Order
    ----------------------------------
    Flavor:      Butter Pecan
    Container:   Cone
    Ingredient:  Peanuts
    Scoops:      1
    Total Price: $2.20
    ==================================
    Press any key to continue . . .
    Ice Cream
  3. Close the DOS window
 

An Array Passed as Argument

The main purpose of using an array is to use various pseudo-variables grouped under one name. Still, an array is primarily a variable. As such, it can be passed to a method and it can be returned from a method. Like a regular variable, an array can be passed as argument. To do this, in the parentheses of a method, provide the data type, the empty square brackets, and the name of the argument. Here is an example:

using System;

namespace ConsoleApplication1
{
    public static class Program
    {
        static void Main()
        {
        }

        static void DisplayNumber(Double[] n)
        {
        }
    }
}

When an array has been passed to a method, it can be used in the body of the method as any array can be, following the rules of array variables. For example, you can display its values. The simplest way you can use an array is to display the values of its members. This could be done as follows:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
        }

        static void DisplayNumber(Double[] n)
        {
            for (int i = 0; i < 5; i++)
                Console.WriteLine("Number {0}: {1}", i, n[i]);
        }
    }
}

To call a method that takes an array as argument, simply type the name of the array in the parentheses of the called method. Here is an example:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            Double[] number = new Double[5];

            number[0] = 12.44;
            number[1] = 525.38;
            number[2] = 6.28;
            number[3] = 2448.32;
            number[4] = 632.04;

            DisplayNumber(number);
        }

        static void DisplayNumber(Double[] n)
        {
            for (int i = 0; i < 5; i++)
                Console.WriteLine("Number {0}: {1}", i, n[i]);
        }
    }
}

This would produce:

Number 0: 12.44
Number 1: 525.38
Number 2: 6.28
Number 3: 2448.32
Number 4: 632.04

When an array is passed as argument to a method, the array is passed by reference. This means that, if the method makes any change to the array, the change would be kept when the method exits. You can use this characteristic to initialize an array from a method. Here is an example:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            Double[] number = new Double[5];

            InitializeList(number);
            DisplayNumber(number);
        }

        static void InitializeList(Double[] nbr)
        {
            nbr[0] = 12.44;
            nbr[1] = 525.38;
            nbr[2] = 6.28;
            nbr[3] = 2448.32;
            nbr[4] = 632.04;
	    // The array has changed
        }

        static void DisplayNumber(Double[] n)
        {
            for (int i = 0; i < 5; i++)
                Console.WriteLine("Number {0}: {1}", i, n[i]);
        }
    }
}

Notice that the InitializeList() method receives an un-initialized array but returns it with new values. To enforce the concept of passing a variable by reference, you can also accompany an array argument with the ref keyword, both when defining the method and when calling it. Here is an example:

using System;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main()
        {
            Double[] number = new Double[5];

            InitializeList(ref number);
            DisplayNumber(ref number);
        }
        static void InitializeList(ref Double[] nbr)
        {
            nbr[0] = 12.44;
            nbr[1] = 525.38;
            nbr[2] = 6.28;
            nbr[3] = 2448.32;
            nbr[4] = 632.04;
        }

        static void DisplayNumber(ref Double[] n)
        {
            for (int i = 0; i < 5; i++)
                Console.WriteLine("Number {0}: {1}", i, n[i]);
        }
    }
}

Practical LearningPractical Learning: Passing an Array as Argument

  1. To use examples of passing arrays to methods, change the IceCreamOrder.cs file as follows:
     
    using System;
    
    namespace IceCream1
    {
        class IceCreamOrder
        {
            public const decimal BasePrice = 1.55M;
    
            int ChoiceFlavor;
            int ChoiceContainer;
            int ChoiceIngredient;
            int Scoops;
            decimal TotalPrice;
    
            private string[] PrepareFlavors()
            {
                string[] Flavors = new string[10];
    
                Flavors[0] = "Vanilla";
                Flavors[1] = "Cream of Cocoa";
                Flavors[2] = "Chocolate Chip";
                Flavors[3] = "Organic Strawberry";
                Flavors[4] = "Butter Pecan";
                Flavors[5] = "Cherry Coke";
                Flavors[6] = "Chocolate Brownies";
                Flavors[7] = "Caramel Au Lait";
                Flavors[8] = "Chunky Butter";
                Flavors[9] = "Chocolate Cookie";
    
                return Flavors;
            }
    
            private void CreateIngredients(ref string[] Ingredients)
            {
                Ingredients[0] = "No Ingredient";
                Ingredients[1] = "Peanuts";
                Ingredients[2] = "M & M";
                Ingredients[3] = "Cookies";
            }
    
            private void ChooseContainer(ref string[] Containers)
            {
                Containers[0] = "Cone";
                Containers[1] = "Cup";
                Containers[2] = "Bowl";
    
                do
                {
                    try
                    {
                      Console.WriteLine("What type of container do you want?");
                        for (int i = 0; i < 3; i++)
                          Console.WriteLine("{0} - {1}", i + 1, Containers[i]);
                        Console.Write("Your Choice? ");
                        ChoiceContainer = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
    Console.WriteLine("You must enter a valid number and no other character!");
                    }
    
                    if (ChoiceContainer < 1 || ChoiceContainer > 3)
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while (ChoiceContainer < 1 || ChoiceContainer > 3);
            }
    
            private void RequestFlavor(ref string[] Flavors)
            {
                Flavors = PrepareFlavors();
    
                do
                {
                    try
                    {
                        Console.WriteLine("What type of flavor do you want?");
                        for (int i = 0; i < 10; i++)
                            Console.WriteLine("{0} - {1}", i + 1, Flavors[i]);
                        Console.Write("Your Choice? ");
                        ChoiceFlavor = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
    Console.WriteLine("You must enter a valid number and no other character!");
                    }
    
                    if (ChoiceFlavor < 1 || ChoiceFlavor > 10)
                        Console.WriteLine("Invalid Choice - Try Again!\n");
                } while (ChoiceFlavor < 1 || ChoiceFlavor > 10);
            }
    
            private void ProcessIngredients(ref string[] Ingredients)
            {
                CreateIngredients(ref Ingredients);
    
                do
                {
                    try
                    {
                        Console.WriteLine("Do you want an ingredient or not");
                        for (int i = 0; i < 4; i++)
                         Console.WriteLine("{0} - {1}", i + 1, Ingredients[i]);
                        Console.Write("Your Choice? ");
                        ChoiceIngredient = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
    Console.WriteLine("You must enter a valid number and no other character!");
                    }
    
                    if (ChoiceIngredient < 1 || ChoiceIngredient > 4)
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while (ChoiceIngredient < 1 || ChoiceIngredient > 4);
            }
    
            private void GetTheNumberOfScoops()
            {
                do
                {
                    try
                    {
                        Console.Write("How many scoops(1, 2, or 3)? ");
                        Scoops = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
    Console.WriteLine("You must enter a valid number and no other character!");
                    }
    
                    if (Scoops < 1 || Scoops > 3)
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while (Scoops < 1 || Scoops > 3);
            }
    
            public void ProcessAnOrder()
            {
                decimal PriceIngredient, PriceScoop;
    
                string[] Flavor = new string[10];
                string[] Container = new string[3];
                string[] Ingredient = new string[4];
    
                RequestFlavor(ref Flavor);
                ChooseContainer(ref Container);
                ProcessIngredients(ref Ingredient);
                GetTheNumberOfScoops();
    
                if (ChoiceIngredient == 2 ||
    		ChoiceIngredient == 3 ||
    		ChoiceIngredient == 4)
                    PriceIngredient = 0.50M;
                else
                    PriceIngredient = 0.00M;
    
                if (Scoops == 1)
                    PriceScoop = 0.65M;
                else if (Scoops == 2)
                    PriceScoop = 1.05M;
                else
                    PriceScoop = 1.55M;
    
                Console.WriteLine("Ice Cream Vendor Machine");
    
                TotalPrice = BasePrice + PriceScoop + PriceIngredient;
    
                DisplayReceipt(ref Flavor, ref Container, ref Ingredient);
            }
    
            public void DisplayReceipt(ref string[] Flv,
    				   ref string[] Cont,
    				   ref string[] Ingrd)
            {
                Console.WriteLine("\n==================================");
                Console.WriteLine("Ice Cream Order");
                Console.WriteLine("----------------------------------");
                Console.WriteLine("Flavor:      {0}", Flv[ChoiceFlavor]);
                Console.WriteLine("Container:   {0}", Cont[ChoiceContainer]);
                Console.WriteLine("Ingredient:  {0}", Ingrd[ChoiceIngredient]);
                Console.WriteLine("Scoops:      {0}", Scoops);
                Console.WriteLine("Total Price: {0:C}", TotalPrice);
                Console.WriteLine("==================================");
            }
        }
    }       
  2. Execute the application and test it
  3. Close the DOS window

Returning an Array From a Method

Like a normal variable, an array can be returned from a method. This means that the method would return a variable that carries various values. When declaring or defining the method, you must specify its data type. When the method ends, it would return an array represented by the name of its variable.

To declare a method that returns an array, on the left of the method's name, provide the type of value that the returned array  will be made of, followed by empty square brackets. Here is an example:

using System;

namespace ConsoleApplication1
{
    public static class Program
    {
        static void Main()
        {
            Double[] number = new Double[5];

            DisplayNumber(number);
        }

        static Double[] InitializeList()
        {
        }

        static void DisplayNumber(Double[] n)
        {
            for (int i = 0; i < 5; i++)
                Console.WriteLine("Number {0}: {1}", i, n[i]);
        }
    }
}

Remember that a method must always return an appropriate value depending on how it was declared. In this case, if it was specified as returning an array, then make sure it returns an array and not a regular variable. One way you can do this is to declare and possibly initialize a local array variable. After using the local array, you return only its name (without the square brackets). Here is an example:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            Double[] number = new Double[5];

            DisplayNumber(number);
            Console.ReadLine();
        }

        static Double[] InitializeList()
        {
            Double[] nbr = new Double[5];

            nbr[0] = 12.44;
            nbr[1] = 525.38;
            nbr[2] = 6.28;
            nbr[3] = 2448.32;
            nbr[4] = 632.04;

            return nbr;
        }

        static void DisplayNumber(Double[] n)
        {
            for (int i = 0; i < 5; i++)
                Console.WriteLine("Number {0}: {1}", i, n[i]);
        }
    }
}

When a method returns an array, that method can be assigned to an array declared locally when you want to use it. Remember to initialize a variable with such a method only if the variable is an array. If you initialize an array variable with a method that doesn't return an array, you would receive an error.

Here is an example:

#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Double[] number = new Double[5];

            number = InitializeList();
            DisplayNumber(number);
            
            Console.ReadLine();
        }

        static Double[] InitializeList()
        {
            Double[] nbr = new Double[5];

            nbr[0] = 12.44;
            nbr[1] = 525.38;
            nbr[2] = 6.28;
            nbr[3] = 2448.32;
            nbr[4] = 632.04;

            return nbr;
        }

        static void DisplayNumber(Double[] n)
        {
            Console.WriteLine("List of Numbers");
            for (int i = 0; i < 5; i++)
                Console.WriteLine("Number {0}: {1}", i, n[i]);
        }
    }
}

Practical LearningPractical Learning: Returning an Array From a Method

  1. To apply an example of returning an array from a method, and to complete this exercise, change the IceCreamOrder.cs file as follows:
     
    using System;
    
    namespace IceCream1
    {
        class IceCreamOrder
        {
            public const decimal BasePrice = 1.55M;
    
            int ChoiceFlavor;
            int ChoiceContainer;
            int ChoiceIngredient;
            int Scoops;
            decimal TotalPrice;
    
            private string[] PrepareFlavors()
            {
                string[] Flavors = new string[10];
    
                Flavors[0] = "Vanilla";
                Flavors[1] = "Cream of Cocoa";
                Flavors[2] = "Chocolate Chip";
                Flavors[3] = "Organic Strawberry";
                Flavors[4] = "Butter Pecan";
                Flavors[5] = "Cherry Coke";
                Flavors[6] = "Chocolate Brownies";
                Flavors[7] = "Caramel Au Lait";
                Flavors[8] = "Chunky Butter";
                Flavors[9] = "Chocolate Cookie";
    
                return Flavors;
            }
    
            private void CreateIngredients(ref string[] Ingredients)
            {
                Ingredients[0] = "No Ingredient";
                Ingredients[1] = "Peanuts";
                Ingredients[2] = "M & M";
                Ingredients[3] = "Cookies";
            }
    
            private void ChooseContainer(ref string[] Containers)
            {
                Containers[0] = "Cone";
                Containers[1] = "Cup";
                Containers[2] = "Bowl";
    
                do
                {
                    try
                    {
                      Console.WriteLine("What type of container do you want?");
                        for (int i = 0; i < 3; i++)
                          Console.WriteLine("{0} - {1}", i + 1, Containers[i]);
                        Console.Write("Your Choice? ");
                        ChoiceContainer = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
    Console.WriteLine("You must enter a valid number and no other character!");
                    }
    
                    if (ChoiceContainer < 1 || ChoiceContainer > 3)
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while (ChoiceContainer < 1 || ChoiceContainer > 3);
            }
    
            private void RequestFlavor(ref string[] Flavors)
            {
                Flavors = PrepareFlavors();
    
                do
                {
                    try
                    {
                        Console.WriteLine("What type of flavor do you want?");
                        for (int i = 0; i < 10; i++)
                            Console.WriteLine("{0} - {1}", i + 1, Flavors[i]);
                        Console.Write("Your Choice? ");
                        ChoiceFlavor = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
    Console.WriteLine("You must enter a valid number and no other character!");
                    }
    
                    if (ChoiceFlavor < 1 || ChoiceFlavor > 10)
                        Console.WriteLine("Invalid Choice - Try Again!\n");
                } while (ChoiceFlavor < 1 || ChoiceFlavor > 10);
            }
    
            private void ProcessIngredients(ref string[] Ingredients)
            {
                CreateIngredients(ref Ingredients);
    
                do
                {
                    try
                    {
                        Console.WriteLine("Do you want an ingredient or not");
                        for (int i = 0; i < 4; i++)
                        Console.WriteLine("{0} - {1}", i + 1, Ingredients[i]);
                        Console.Write("Your Choice? ");
                        ChoiceIngredient = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
    Console.WriteLine("You must enter a valid number and no other character!");
                    }
    
                    if (ChoiceIngredient < 1 || ChoiceIngredient > 4)
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while (ChoiceIngredient < 1 || ChoiceIngredient > 4);
            }
    
            private void GetTheNumberOfScoops()
            {
                do
                {
                    try
                    {
                        Console.Write("How many scoops(1, 2, or 3)? ");
                        Scoops = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
    Console.WriteLine("You must enter a valid number and no other character!");
                    }
    
                    if (Scoops < 1 || Scoops > 3)
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while (Scoops < 1 || Scoops > 3);
            }
    
            public void ProcessAnOrder()
            {
                decimal PriceIngredient, PriceScoop;
    
                string[] Flavor = new string[10];
                string[] Container = new string[3];
                string[] Ingredient = new string[4];
    
                RequestFlavor(ref Flavor);
                ChooseContainer(ref Container);
                ProcessIngredients(ref Ingredient);
                GetTheNumberOfScoops();
    
                if (ChoiceIngredient == 2 ||
    		ChoiceIngredient == 3 ||
    		ChoiceIngredient == 4)
                    PriceIngredient = 0.50M;
                else
                    PriceIngredient = 0.00M;
    
                if (Scoops == 1)
                    PriceScoop = 0.65M;
                else if (Scoops == 2)
                    PriceScoop = 1.05M;
                else
                    PriceScoop = 1.55M;
    
                Console.WriteLine("Ice Cream Vendor Machine");
    
                TotalPrice = BasePrice + PriceScoop + PriceIngredient;
    
                DisplayReceipt(ref Flavor, ref Container, ref Ingredient);
            }
    
            public void DisplayReceipt(ref string[] Flv,
    				   ref string[] Cont,
    				   ref string[] Ingrd)
            {
                Console.WriteLine("\n==================================");
                Console.WriteLine("Ice Cream Order");
                Console.WriteLine("----------------------------------");
                Console.WriteLine("Flavor:      {0}", Flv[ChoiceFlavor]);
                Console.WriteLine("Container:   {0}", Cont[ChoiceContainer]);
                Console.WriteLine("Ingredient:  {0}", Ingrd[ChoiceIngredient]);
                Console.WriteLine("Scoops:      {0}", Scoops);
                Console.WriteLine("Total Price: {0:C}", TotalPrice);
                Console.WriteLine("==================================");
            }
        }
    }
  2. Execute the application and test it. Here is an example:
     
    What type of flavor do you want?
    1 - Vanilla
    2 - Cream of Cocoa
    3 - Chocolate Chip
    4 - Organic Strawberry
    5 - Butter Pecan
    6 - Cherry Coke
    7 - Chocolate Brownies
    8 - Caramel Au Lait
    9 - Chunky Butter
    10 - Chocolate Cookie
    Your Choice? 9
    What type of container do you want?
    1 - Cone
    2 - Cup
    3 - Bowl
    Your Choice? 2
    Do you want an ingredient or not
    1 - No Ingredient
    2 - Peanuts
    3 - M & M
    4 - Cookies
    Your Choice? 3
    How many scoops(1, 2, or 3)? 2
    Ice Cream Vendor Machine
    
    ==================================
    Ice Cream Order
    ----------------------------------
    Flavor:      Chocolate Cookie
    Container:   Bowl
    Ingredient:  Cookies
    Scoops:      2
    Total Price: $3.10
    ==================================
    Press any key to continue . . .
    Ice Cream
  3. Close the DOS window
 

Previous Copyright © 2006-2016, FunctionX, Inc. Next