Home

Arrays of Primitive Types

   

An Array of a Primitive Type as a Field

 

Introduction

As we have used them so far, an array is primarily a variable. As such, it can be declared as a member variable of a class. To create a field as an array, you can declare it like a normal array in the body of the class. Here is an example:

   

public class CoordinateSystem
{
    private int[] points;
}

Like any field, when an array has been declared as a member variable, it is made available to all the other members of the same class. You can use this feature to initialize the array in one method and let other methods use the initialized variable. This also means that you don't have to pass the array as argument nor do you have to explicitly return it from a method.

After or when declaring an array, you must make sure you allocate memory for it prior to using. Unlike C++, you can allocate memory for an array when declaring it. Here is an example:

public class CoordinateSystem
{
    private int[] points = new int[4];
}

You can also allocate memory for an array field in a constructor of the class. Here is an example:

public class CoordinateSystem
{
    private int[] points;

    public CoordinateSystem()
    {
        points = new int[4];
    }
}

If you plan to use the array as soon as the program is running, you can initialize it using a constructor or a method that you know would be called before the array can be used. Here is an example:

public class CoordinateSystem
{
    private int[] points;

    public CoordinateSystem()
    {
        points = new int[4];

        points[0] = 2;
        points[1] = 5;
        points[2] = 2;
        points[3] = 8;
    }
}

ApplicationApplication: Introducing Arrays and Classes

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New Project...
  3. In the middle list, click Empty Project
  4. Change the Name to RentalProperties1 and press Enter
  5. To create a new class, in the Class View, right-click RenatlProperties1 -> Add -> Class...
  6. Set the Name to RentalProperty and press Enter
  7. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace RentalProperties1
    {
        public enum PropertyType
        {
        	SingleFamily, Townhouse,
            Apartment, Unknown
        };
    
        public class RentalProperty
        {
            private long[] propertyNumbers;
            private PropertyType[] types;
            private short[] beds;
            private float[] baths;
            private double[] monthlyRents;
    
            public RentalProperty()
            {
                propertyNumbers = new long[] {
                    192873, 498730, 218502, 612739,
                    457834, 927439, 570520, 734059 };
    
                types = new PropertyType[] {
                    PropertyType.SingleFamily, PropertyType.SingleFamily, 
                    PropertyType.Apartment, PropertyType.Apartment,
                    PropertyType.Townhouse, PropertyType.Apartment,
                    PropertyType.Apartment, PropertyType.Townhouse };
    
                beds = new short[] { 5, 4, 2, 1, 3, 1, 3, 4 };
    
                baths = new float[] { 3.50F, 2.50F, 1.00F, 1.00F,
                                      2.50F, 1.00F, 2.00F, 1.50F };
    
                monthlyRents = new double[] {
                    2250.00D, 1885.00D, 1175.50D, 945.00D,
                    1750.50D, 1100.00D, 1245.95D, 1950.25D };
            }
        }
    }

Presenting the Array

After an array has been created as a field, it can be used by any other member of the same class. Based on this, you can use a member of the same class to request values that would initialize it. You can also use another method to explore the array. Here is an example:

using System;

public class CoordinateSystem
{
    private int[] points;

    public CoordinateSystem()
    {
        points = new int[4];

        points[0] = 2;
        points[1] = -5;
        points[2] = 2;
        points[3] = 8;
    }

    public void ShowPoints()
    {
        Console.WriteLine("Points Coordinates");
        Console.WriteLine("P({0}, {1})", points[0], points[1]);
        Console.WriteLine("Q({0}, {1})", points[2], points[3]);
    }
}

public class Exercise
{
    static int Main()
    {
        var Coordinates = new CoordinateSystem();

        Coordinates.ShowPoints();
        return 0;
    }
}

This would produce:

Points Coordinates
P(2, -5)
Q(2, 8)
Press any key to continue . . .

ApplicationApplication: Presenting an Array

  1. To prepare the class to show the values of the array, change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace RentalProperties1
    {
        public enum PropertyType { SingleFamily, Townhouse,
                                   Apartment, Unknown };
    
        public class RentalProperty
        {
            private long[] propertyNumbers;
            private PropertyType[] types;
            private short[] beds;
            private float[] baths;
            private double[] monthlyRents;
    
            public RentalProperty()
            {
                propertyNumbers = new long[] {
                    192873, 498730, 218502, 612739,
                    457834, 927439, 570520, 734059 };
    
                types = new PropertyType[] {
                    PropertyType.SingleFamily, PropertyType.SingleFamily, 
                    PropertyType.Apartment, PropertyType.Apartment,
                    PropertyType.Townhouse, PropertyType.Apartment,
                    PropertyType.Apartment, PropertyType.Townhouse };
    
                beds = new short[] { 5, 4, 2, 1, 3, 1, 3, 4 };
    
                baths = new float[] { 3.50F, 2.50F, 1.00F, 1.00F,
                                          2.50F, 1.00F, 2.00F, 1.50F };
    
                monthlyRents = new double[] {
                    2250.00D, 1885.00D, 1175.50D, 945.00D,
                    1750.50D, 1100.00D, 1245.95D, 1950.25D };
            }
    
            public void ShowListing()
            {
                Console.WriteLine("Properties Listing");
                Console.WriteLine("=============================================");
                Console.WriteLine("Prop #  Property Type Beds Baths Monthly Rent");
                Console.WriteLine("---------------------------------------------");
                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("{0}\t{1}\t{2}  {3:F}{4,12}",
                        propertyNumbers[i], types[i], beds[i],
                        baths[i], monthlyRents[i].ToString("F"));
                }
                Console.WriteLine("=============================================");
            }
        }
    }
  2. To create a new file, in the Solution Explorer, right-click RenatlProperties1 -> Add -> New Item...
  3. In the middle list, click Code File
  4. Change the Name to RentalProperties and press Enter
  5. In the empty document, type the following:
    using System;
    using RentalProperties1;
    
    public class PropertiesReview
    {
        public static int Main()
        {
            RentalProperty Property = new RentalProperty();
    
            Console.Title = "Solas Rental Properties";
    
            Property.ShowListing();
            
            Console.ReadKey();
            return 0;
        }
    }
  6. To execute the application to see the result, press F5
    Properties Listing
    =============================================
    Prop #  Property Type Beds Baths Monthly Rent
    ---------------------------------------------
    192873  SingleFamily    5  3.50     2250.00
    498730  SingleFamily    4  2.50     1885.00
    218502  Apartment       2  1.00     1175.50
    612739  Apartment       1  1.00      945.00
    457834  Townhouse       3  2.50     1750.50
    927439  Apartment       1  1.00     1100.00
    570520  Apartment       3  2.00     1245.95
    734059  Townhouse       4  1.50     1950.25
    =============================================
  7. Press Enter to close the DOS window and return to your programming environment
  8. On the main menu, click File -> Close Solution
  9. When asked whether you want to save, click Discard

Arrays and Methods

 

Introduction

Each member of an array holds a legitimate value. Therefore, 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.

The main purpose of using an array is to use various values 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.

ApplicationApplication: Introducing Arrays and Methods

  1. To create a new application, on the main menu, click File -> New Project...
  2. In the middle list, click Empty Project
  3. Change the Name to PayrollPreparation1 and press Enter
  4. To create a new file, in the Solution Explorer, right-click PayrollPreparation1 -> Add -> New Item...
  5. In the middle list, click Code File
  6. Change the Name to PayrollPreparation and press Enter
  7. Change the document as follows:
    using System;
    
    public class PayrollPreparation
    {
        public static int Main()
        {
        	Console.ReadKey();
            return 0;
        }
    }

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.

You can create a method that takes an array as argument and returns another array as argument.

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;

public class CoordinateSystem
{
    public int[] Initialize()
    {
    }
}

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;

public class CoordinateSystem
{
    public int[] Initialize()
    {
        var coords = new int[] { 12, 5, -2, -2 };

        return coords;
    }
}

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. 

Here is an example:

using System;

public class CoordinateSystem
{
    public int[] Initialize()
    {
        var coords = new int[] { 12, 5, -2, -2 };

        return coords;
    }
}

public class Exercise
{
    static int Main()
    {
        var system = new int[4];
        var coordinates = new CoordinateSystem();

        system = coordinates.Initialize();

        return 0;
    }
}

The method could also be called as follows:

public class Exercise
{
    static int Main()
    {
        var coordinates = new CoordinateSystem();

        var system = coordinates.Initialize();

        return 0;
    }
}

If you initialize an array variable with a method that doesn't return an array, you would receive an error.

ApplicationApplication: Returning an Array From a Method

  • To create a method that returns an array, change the PayrollPreparation.cs document as follows:
    using System;
    
    public class PayrollPreparation
    {
        public double[] PreparePayroll(out double Salary,
                                       out double Time)
        {
            Salary = 0D;
            Time = 0D;
            double[] Values = new double[6];
    
            try
            {
                Console.Write("Enter Hourly Salary: ");
                Salary = double.Parse(Console.ReadLine());
            }
            catch (FormatException)
            {
                Console.WriteLine("Invalid Hourly Salary");
            }
    
            try
            {
                Console.Write("Enter Time Worked: ");
                Time = double.Parse(Console.ReadLine());
            }
            catch (FormatException)
            {
                Console.WriteLine("Invalid Time Workd");
            }
    
            if (Time <= 40)
            {
                Values[0] = Time;
                Values[1] = 0;
                Values[2] = 0;
            }
            else // if (Time <= 40)
            {
                Values[0] = 40;
                Values[1] = Time - Values[0];
                Values[2] = Salary + (Salary / 2);
            }
    
            Values[3] = Salary * Values[0];
            Values[4] = Values[2] * Values[1];
            Values[5] = Values[3] + Values[4];
    
            return Values;
        }
    
        public static int Main()
        {
            // This variable holds the employee's
            double HourlySalary = 0D;
            // This variable will hold the total time the 
            // employee worked for the week
            double TimeWorked = 0D;
            PayrollPreparation pp = new PayrollPreparation();
    
            // To process our payroll, we will use an array of 6 elements 
            // with the following values
            // Element[0]: Regular Time
            //             This will hold the time if the employee worked
            //             for 40 or less hours in the week
            // Element[1]: Over Time
            //             This will be the time the employee worked if over 40 hours
            // Element[2]: Over Time Salary
            //             This will be the time and half if the employee
            //             worked more than 40 hours for the week
            // Element[3]: Regular Pay
            //             This will be the regular salary for less than 40 hours
            // Element[4]: Overtime Pay
            //             This will be the pay corresponding to the over time
            // Element[5]: Gross Pay:
            //             This will be the employee's weekly salary
            double[] Payroll = new double[6];
    
            Console.Title = "Payroll Preparation";
    
            Payroll = pp.PreparePayroll(out HourlySalary, out TimeWorked);
            
            Console.ReadKey();
            return 0;
        }
    }

An Array Passed as Argument

Like a regular variable, an array can be passed as argument. To proceed, in the parentheses of a method, provide the data type, the empty square brackets, and the name of the argument. Here is an example:

public class CoordinateSystem
{
    public void ShowPoints(int[] points)
    {
    }
}

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:

public class CoordinateSystem
{
    public void ShowPoints(int[] points)
    {
        Console.WriteLine("Points Coordinates");
        Console.WriteLine("P({0}, {1})", points[0], points[1]);
        Console.WriteLine("Q({0}, {1})", points[2], points[3]);
    }
}

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;

public class CoordinateSystem
{
    public void ShowPoints(int[] points)
    {
        Console.WriteLine("Points Coordinates");
        Console.WriteLine("P({0}, {1})", points[0], points[1]);
        Console.WriteLine("Q({0}, {1})", points[2], points[3]);
    }
}

public class Exercise
{
    static int Main()
    {
        var points = new int[] { -3, 3, 6, 3 };
        var coordinates = new CoordinateSystem();

        coordinates.ShowPoints(points);
        return 0;
    }
}

This would produce:

Points Coordinates
P(-3, 3)
Q(6, 3)
Press any key to continue . . .

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;

public class CoordinateSystem
{
    public void Initialize(int[] coords)
    {
        coords[0] = -4;
        coords[1] = -2;
        coords[2] = -6;
        coords[3] =  3;
    }

    public void ShowPoints(int[] points)
    {
        Console.WriteLine("Points Coordinates");
        Console.WriteLine("P({0}, {1})", points[0], points[1]);
        Console.WriteLine("Q({0}, {1})", points[2], points[3]);
    }
}

public class Exercise
{
    static int Main()
    {
        var system = new int[4];
        var coordinates = new CoordinateSystem();

        coordinates.Initialize(system);
        coordinates.ShowPoints(system);

        return 0;
    }
}

This would produce:

Points Coordinates
P(-4, -2)
Q(-6, 3)
Press any key to continue . . .

ApplicationApplication: Passing an Arrays as Argument

  1. To pass an array to a method, change the PayrollPreparation.cs file as follows:
    using System;
    
    public class PayrollPreparation
    {
        public double[] PreparePayroll(out double Salary,
                                       out double Time)
        {
            Salary = 0D;
            Time = 0D;
            double[] Values = new double[6];
    
            try
            {
                Console.Write("Enter Hourly Salary: ");
                Salary = double.Parse(Console.ReadLine());
            }
            catch (FormatException)
            {
                Console.WriteLine("Invalid Hourly Salary");
            }
    
            try
            {
                Console.Write("Enter Time Worked: ");
                Time = double.Parse(Console.ReadLine());
            }
            catch (FormatException)
            {
                Console.WriteLine("Invalid Time Workd");
            }
    
            if (Time <= 40)
            {
                Values[0] = Time;
                Values[1] = 0;
                Values[2] = 0;
            }
            else // if (Time <= 40)
            {
                Values[0] = 40;
                Values[1] = Time - Values[0];
                Values[2] = Salary + (Salary / 2);
            }
    
            Values[3] = Salary * Values[0];
            Values[4] = Values[2] * Values[1];
            Values[5] = Values[3] + Values[4];
    
            return Values;
        }
    
        public void ShowPayroll(double Salary,
                                double Time,
                                double[] Results)
        {
            Console.WriteLine("========================");
            Console.WriteLine("Georgetown Dry Cleaners");
            Console.WriteLine("------------------------");
            Console.WriteLine("Hourly Salary:{0, 9}",
                Salary.ToString("F"));
            Console.WriteLine("Time Worked:{0, 11}",
                Time.ToString("F"));
            Console.WriteLine("Regular Time:{0, 10}",
                Results[0].ToString("F"));
            Console.WriteLine("Overtime:{0,14}",
                Results[1].ToString("F"));
            Console.WriteLine("Overtime Salary:{0, 7}",
                Results[2].ToString("F"));
            Console.WriteLine("Regular Pay:{0, 11}",
                Results[3].ToString("F"));
            Console.WriteLine("Overtime Pay:{0, 10}",
                Results[4].ToString("F"));
            Console.WriteLine("Gross Pay:{0, 13}",
                Results[5].ToString("F"));
            Console.WriteLine("========================");
        }
    
        public static int Main()
        {
            // This variable holds the employee's
            double HourlySalary = 0D;
            // This variable will hold the total time the 
            // employee worked for the week
            double TimeWorked = 0D;
            PayrollPreparation pp = new PayrollPreparation();
    
            // To process our payroll, we will use an array of 6 elements 
            // with the following values
            // Element[0]: Regular Time
            //             This will hold the time if the employee worked
            //             for 40 or less hours in the week
            // Element[1]: Over Time
            //             This will be the time the employee worked if over 40 hours
            // Element[2]: Over Time Salary
            //             This will be the time and half if the employee
            //             worked more than 40 hours for the week
            // Element[3]: Regular Pay
            //             This will be the regular salary for less than 40 hours
            // Element[4]: Overtime Pay
            //             This will be the pay corresponding to the over time
            // Element[5]: Gross Pay:
            //             This will be the employee's weekly salary
            double[] Payroll = new double[6];
    
            Console.Title = "Payroll Preparation";
    
            Payroll = pp.PreparePayroll(out HourlySalary, out TimeWorked);
            
            Console.Clear();
            pp.ShowPayroll(HourlySalary, TimeWorked, Payroll);
            
            Console.ReadKey();
            return 0;
        }
    }
  2. To execute the application to test it, press F5
  3. Type the hourly salary as 25.50 and press Enter
  4.  Enter a time worked that is less than 40, for example 36.00
    Enter Hourly Salary: 25.50
    Enter Time Worked: 36.00
  5. Press Enter:
    ========================
    Georgetown Dry Cleaners
    ------------------------
    Hourly Salary:    25.50
    Time Worked:      36.00
    Regular Time:     36.00
    Overtime:          0.00
    Overtime Salary:   0.00
    Regular Pay:     918.00
    Overtime Pay:      0.00
    Gross Pay:       918.00
    ========================
    Press any key to continue . . .
  6. Press Enter to close the DOS window and return to your programming environment
  7. To execute the application again, press F5
  8. Type the hourly salary as 22.65 and press Enter
  9.  Type the time worked as 46.50
    Enter Hourly Salary: 22.65
    Enter Time Worked: 46.50
  10. Press Enter
    ========================
    Georgetown Dry Cleaners
    ------------------------
    Hourly Salary:    22.65
    Time Worked:      46.50
    Regular Time:     40.00
    Overtime:          6.50
    Overtime Salary:  33.98
    Regular Pay:     906.00
    Overtime Pay:    220.84
    Gross Pay:      1126.84
    ========================
    Press any key to continue . . .
  11. Press Enter to close the DOS window and return to your programming environment

	

Other Techniques of Passing Arrays as Arguments

  

Passing an Array By Reference

Consider the following code from what we saw earlier:

using System;

public class CoordinateSystem
{
    public void ShowPoints(int[] points)
    {
        Console.WriteLine("In ShowPoints() - Points Coordinates");
        Console.WriteLine("P({0}, {1})", points[0], points[1]);
        Console.WriteLine("Q({0}, {1})", points[2], points[3]);
    }
}

public class Exercise
{
    static int Main()
    {
        var system = new int[4];
        var coordinates = new CoordinateSystem();

        Console.WriteLine("In Main() - Points Coordinates");
        Console.WriteLine("P({0}, {1})", system[0], system[1]);
        Console.WriteLine("Q({0}, {1})", system[2], system[3]);

        coordinates.ShowPoints(system);

        Console.WriteLine("In Main() - Points Coordinates");
        Console.WriteLine("P({0}, {1})", system[0], system[1]);
        Console.WriteLine("Q({0}, {1})", system[2], system[3]);

        return 0;
    }
}

This would produce:

In Main() - Points Coordinates
P(0, 0)
Q(0, 0)
In ShowPoints() - Points Coordinates
P(0, 0)
Q(0, 0)
In Main() - Points Coordinates
P(0, 0)
Q(0, 0)
Press any key to continue . . .

Notice that the ShowPoints() method receives an array whose elements don't have values. The array is initialized in Main(). An array is a reference-type. This means that when an element of an array is accessed, it is actually the memory address of where it resides that is accessed, not the value itself. Consequently, when an array is passed as argument, it is automatically passed by reference. This means that the method that receives the argument can change it and if it does, the value of the element is permanently changed. Consider the following code:

using System;

public class CoordinateSystem
{
    public void ShowPoints(int[] points)
    {
        points[0] = 2;
        points[1] = -4;
        points[2] = 6;
        points[3] = 3;

        Console.WriteLine("In ShowPoints() - Points Coordinates");
        Console.WriteLine("P({0}, {1})", points[0], points[1]);
        Console.WriteLine("Q({0}, {1})", points[2], points[3]);
    }
}

public class Exercise
{
    static int Main()
    {
        var system = new int[4];
        var coordinates = new CoordinateSystem();

        Console.WriteLine("In Main() - Points Coordinates");
        Console.WriteLine("P({0}, {1})", system[0], system[1]);
        Console.WriteLine("Q({0}, {1})", system[2], system[3]);

        coordinates.ShowPoints(system);

        Console.WriteLine("In Main() - Points Coordinates");
        Console.WriteLine("P({0}, {1})", system[0], system[1]);
        Console.WriteLine("Q({0}, {1})", system[2], system[3]);

        return 0;
    }
}

This would produce:

In Main() - Points Coordinates
P(0, 0)
Q(0, 0)
In ShowPoints() - Points Coordinates
P(2, -4)
Q(6, 3)
In Main() - Points Coordinates
P(2, -4)
Q(6, 3)
Press any key to continue . . .

Again, notice that the ShowPoints() function receives an array without values but it changes it. When this function exits, the elements of the array have received values and Main() gets back the array with new values. It is important to understand that this ShowPoints() method doesn't initialize the array. It only changes the values of the elements of the array. This is further illustrated in the following code:

using System;

public class CoordinateSystem
{
    public void ShowPoints(int[] points)
    {
        Console.WriteLine("Entering ShowPoints() - Points Coordinates");
        Console.WriteLine("P({0}, {1})", points[0], points[1]);
        Console.WriteLine("Q({0}, {1})", points[2], points[3]);

        points[0] = 2;
        points[1] = -4;
        points[2] = 6;
        points[3] = 3;

        Console.WriteLine("Exiting ShowPoints() - Points Coordinates");
        Console.WriteLine("P({0}, {1})", points[0], points[1]);
        Console.WriteLine("Q({0}, {1})", points[2], points[3]);
    }
}

public class Exercise
{
    static int Main()
    {
        var system = new int[4];
        var coordinates = new CoordinateSystem();

        system[0] = -10;
        system[1] = 0;
        system[2] = 5;
        system[3] = -2;

        Console.WriteLine("Starting in Main() - Points Coordinates");
        Console.WriteLine("P({0}, {1})", system[0], system[1]);
        Console.WriteLine("Q({0}, {1})", system[2], system[3]);

        coordinates.ShowPoints(system);

        Console.WriteLine("After Calling ShowPoints: In Main() - Points Coordinates");
        Console.WriteLine("P({0}, {1})", system[0], system[1]);
        Console.WriteLine("Q({0}, {1})", system[2], system[3]);

        return 0;
    }
}

This would produce:

Starting in Main() - Points Coordinates
P(-10, 0)
Q(5, -2)
Entering ShowPoints() - Points Coordinates
P(-10, 0)
Q(5, -2)
Exiting ShowPoints() - Points Coordinates
P(2, -4)
Q(6, 3)
After Calling ShowPoints: In Main() - Points Coordinates
P(2, -4)
Q(6, 3)
Press any key to continue . . .

Still, if you want, you can re-initialize the array by allocating new memory to it.

To enforce the concept of passing an array by reference, you can accompany the argument with the ref keyword, both when defining the method and when calling it. Here is an example:

using System;

public class CoordinateSystem
{
    public void ShowPoints(ref int[] points)
    {
        Console.WriteLine("In ShowPoints() - Points Coordinates");
        Console.WriteLine("P({0}, {1})", points[0], points[1]);
        Console.WriteLine("Q({0}, {1})", points[2], points[3]);
    }
}

public class Exercise
{
    static int Main()
    {
        var system = new int[4];
        var coordinates = new CoordinateSystem();

        system[0] = -10;
        system[1] = 0;
        system[2] = 5;
        system[3] = -2;

        coordinates.ShowPoints(ref system);

        Console.WriteLine("In Main() - Points Coordinates");
        Console.WriteLine("P({0}, {1})", system[0], system[1]);
        Console.WriteLine("Q({0}, {1})", system[2], system[3]);

        return 0;
    }
}

Instead of just one, you can create a method that receives more than one array and you can create a method that receives a combination of one or more arrays and one or more regular arguments. You can also create a method that takes one or more arrays as argument(s) and returns a regular value of a primitive type.

Passing an Array Out

As seen for passing an argument by reference, you can pass an array out. We saw that, when passing an array using the ref keyword, the method that receives the array doesn't have to initialize it. If the array was already initialized by the function that is making the call, the called method can simply change the values of the elements of the array. On the other hand, if you pass an array using the out keyword, the method that receives the out array must initialize it before exiting. Here is an example:

using System;

public class CoordinateSystem
{
    public void ShowPoints(out int[] points)
    {
        points = new int[4];
        points[0] = -1;
        points[1] = 7;
        points[2] = 2;
        points[3] = -2;

        Console.Write("In ShowPoints() - Points Coordinates: ");
        Console.Write("P({0}, {1}), ", points[0], points[1]);
        Console.WriteLine("Q({0}, {1})", points[2], points[3]);
    }
}

public class Exercise
{
    static int Main()
    {
        var system = new int[4];
        var coordinates = new CoordinateSystem();

        coordinates.ShowPoints(out system);

        Console.Write("In Main() - Points Coordinates:       ");
        Console.Write("P({0}, {1}), ", system[0], system[1]);
        Console.WriteLine("Q({0}, {1})", system[2], system[3]);

        return 0;
    }
}

This would produce:

In ShowPoints() - Points Coordinates: P(-1, 7), Q(2, -2)
In Main() - Points Coordinates:       P(-1, 7), Q(2, -2)
Press any key to continue . . .

Passing an array as argument by reference makes it possible for a method to return many values.

Passing a Varied Number of Parameters

We saw that you can pass an array as argument, either regularly or by reference. When you call the method that receives that argument, you must pass an array variable to it. We also saw that you can pass more than one array as argument and you can pass a combination of arrays and non-array arguments. When you call the method, you must pass the exact number of arguments. That is, you must know the number of arguemnts the method will process. An alternative to this is to pass only one array as argument. Then, when, or every time, you call the method, you can pass any number of values you want. That is, at one time you can call the method and pass 2 values. At another time you can call the same method but pass 8 arguments to it.

To create a method that receives a varied number of arguments, in the parentheses of the method, type the params keyword followed by an array. Here is an example:

public class CoordinateSystem
{
    public void ShowPoints(params int[] points)
    {
    }
}

As mentioned already, when calling the method, you can pass the number of arguments you want. It's important to know that the method that receives a params argument doesn't know how many arguments it will receive when it is called. This means that you must find a way to access the arguments and you must find a way for the method to know the number of arguments it received. Because this information is not known to the method, the Array class provides a property named Length that holds the size of the array.

Here are examples of calling a method that receives a params argument:

using System;

public class CoordinateSystem
{
    public void ShowPoints(params int[] points)
    {
        int dimension = points.Length;

        if (dimension == 1)
            Console.WriteLine("The point is located on a line");
        else if (dimension == 2)
            Console.WriteLine("The point is located on a Cartesian coordinate system");
        else if (dimension == 3)
            Console.WriteLine("The point is located on a 3-D coordinate system");
        else
            Console.WriteLine("The point is located on a multi-dimensional system");
    }
}

public class Exercise
{
    static int Main()
    {
        var system = new int[4];
        var coordinates = new CoordinateSystem();

        // The method is called with one argument
        coordinates.ShowPoints(-6);
        // The method is called with 4 arguments
         coordinates.ShowPoints(2, 2, 5, -3);
        // The method is called with two arguments
         coordinates.ShowPoints(2, 5);
        // The method is called with three arguments
         coordinates.ShowPoints(-4, 3, 1);

        return 0;
    }
}

This would produce:

The point is located on a line
The point is located on a multi-dimensional system
The point is located on a Cartesian coordinate system
The point is located on a 3-D coordinate system
Press any key to continue . . .

If you decide to create a method that receives a params argument, you can pass only one argument and that would be only the params argument.

 

Previous Copyright © 2010-2016, FunctionX Next