An Array as a Field

Introduction

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 of a class, 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 it.

After, or when, declaring an array, you must make sure you allocate memory prior to using it. As seen for fields of other types, you can allocate memory for an array when declaring it in the body of a class. 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;
    }
}

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 static System.Console;
using static System.Environment;

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()
    {
        string strMessage = "Points Coordinates" + System.Environment.NewLine +
                            "P(" + points[0].ToString() + ", " + points[1].ToString() + ")" + NewLine +
                            "Q(" + points[2].ToString() + ", " + points[1].ToString() + ")";

        WriteLine("Coordinate System");
        WriteLine("-----------------------------------");
        WriteLine(strMessage);
    }
}

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

        Coordinates.ShowPoints();
        WriteLine("===================================");
        return;
    }
}

This would produce:

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

Arrays and Methods

Introduction

Each member of an array holds a value, you can pass a single member of an array as argument or you can pass the name of the array variable with the accompanying index to a method.

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, such as the name of an array variable.

You can create a method that uses an array. To do this, 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:

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 value. 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:

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

        return coords;
    }
}

To call a method that returns an array, you can assign the call to a locally declared array variable. After the call, the local variable holds the array returned by the method and you can that array like any we have used so far. Here is an example:

using static System.Console;

public class CarRental
{
    public string[] GetManufacturers()
    {
        string[] makes = new string[] { "Ford", "Dodge", "Chrysler", "Jeep", "Cadillac" };

        return makes;
    }
}

public class Exercise
{
    public static void Main()
    {
        string[] cars = new string[5];
        CarRental freight = new CarRental();

        cars = freight.GetManufacturers();

        foreach(string make in cars)
            WriteLine("Make: " + make);
        WriteLine("===================================");
        return;
    }
}

This would produce:

Make: Ford
Make: Dodge
Make: Chrysler
Make: Jeep
Make: Cadillac
===================================
Press any key to continue . . .

In our class, we first declared an array variable and inialized it before returning it. This is necessary if you are planing to perform some operaitons on an array before returning it. If you planning to create an array and immediately return it, you can create it directly on the return keyword. Here is an example:

using static System.Console;

public class CarRental
{
    public string[] GetManufacturers()
    {
       return new string[] { "Ford", "Dodge", "Chrysler", "Jeep", "Cadillac" };
    }
}

public class Exercise
{
    public static void Main()
    {
        string[] cars = new string[5];
        CarRental freight = new CarRental();

        cars = freight.GetManufacturers();

        foreach (string make in cars)
            WriteLine("Make: " + make);
        WriteLine("===================================");

        return;
    }
}

In the above code, we first declared an initialized an array variable and used another line call the method. This is not necessary. You can directly assign the method call to the variable while declaring it. Here is an example:

public class Exercise
{
    public static void Main()
    {
        CarRental freight = new CarRental();

        string[] cars = freight.GetManufacturers();

        foreach(string make in cars)
            WriteLine("Make: " + make);
        WriteLine("===================================");
        return;
    }
}

Remember that you can use the var keyword to declare a variable of any type. Here is an example:

public class Exercise
{
    public static void Main()
    {
        CarRental freight = new CarRental();

        var cars = freight.GetManufacturers();

        foreach(string make in cars)
            WriteLine("Make: " + make);
        WriteLine("===================================");
        return;
    }
}

In both casses, if you initialize an array variable with a method that doesn't return an array, you would receive an error.

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:

using static System.Console;

public class CarRental
{
    public string[] GetManufacturers()
    {
        string[] makes = new string[] { "Ford", "Dodge", "Chrysler", "Jeep", "Cadillac" };

        return makes;
    }

    public void Display(string[] makers)
    {
        foreach (string make in makers)
            WriteLine("Make: " + make);
        WriteLine("===================================");
    }
}

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

using static System.Console;

public class CarRental
{
    public string[] GetManufacturers()
    {
       return new string[] { "Ford", "Dodge", "Chrysler", "Jeep", "Cadillac" };
    }

    public void Display(string[] makers)
    {
        foreach (string make in makers)
            WriteLine("Make: " + make);
        WriteLine("===================================");
    }
}

public class Exercise
{
    public static void Main()
    {
        CarRental freight = new CarRental();

        string[] cars = freight.GetManufacturers();

        freight.Display(cars);

        return;
    }
}

In the above code, we first declared an array variable before passing it to a method call. This is necessary if you have to process the array before calling the method. If you don't need to use the array before passing it to the mathod, you can create the array directly in the parentheses of the method you are calling. Here is an example:

using static System.Console;

public class CarRental
{
    public void Display(string[] makers)
    {
        foreach (string make in makers)
            WriteLine("Make: " + make);
        WriteLine("===================================");
    }
}

public class Exercise
{
    public static void Main()
    {
        CarRental freight = new CarRental();

        freight.Display(new string[] { "Ford", "Dodge", "Chrysler", "Jeep", "Cadillac" });

        return;
    }
}

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 static System.Console;
using static System.Environment;

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

    public void ShowPoints(int[] pts)
    {
        string strMessage = "Points Coordinates" + NewLine +
                            "P(" + pts[0].ToString() + ", " + pts[1].ToString() + ")" + NewLine +
                            "Q(" + pts[2].ToString() + ", " + pts[3].ToString() + ")";

        WriteLine("Coordinate System");
        WriteLine(strMessage);
    }
}

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

        coordinates.Initialize(system);
        coordinates.ShowPoints(system);
        WriteLine("===================================");

        return;
    }
}

Other Techniques of Passing Arrays as Arguments

Passing an Array By Reference

Consider the following code from what we know so far:

using static System.Console;

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

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

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

        coordinates.ShowPoints(system);
        WriteLine("-------------------------------------");

        WriteLine("Back in Main() - Points Coordinates");
        WriteLine("P(" + system[0].ToString() + ", " + system[1].ToString() + ")");
        WriteLine("Q(" + system[2].ToString() + ", " + system[3].ToString() + ")");
        WriteLine("=====================================");
        
    }
}

This would produce:

In Main() - Points Coordinates
P(0, 0)
Q(0, 0)
-------------------------------------
In ShowPoints() - Points Coordinates
P(0, 0)
Q(0, 0)
-------------------------------------
Back 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 the Main() method. As seen earlier, 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 static System.Console;

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

        WriteLine("In ShowPoints() - Points Coordinates");
        WriteLine("P(" + pts[0].ToString() + ", " + pts[1].ToString() + ")");
        WriteLine("Q(" + pts[2].ToString() + ", " + pts[3].ToString() + ")");
    }
}

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

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

        coordinates.ShowPoints(system);
        WriteLine("-------------------------------------");

        WriteLine("Back in Main() - Points Coordinates");
        WriteLine("P(" + system[0].ToString() + ", " + system[1].ToString() + ")");
        WriteLine("Q(" + system[2].ToString() + ", " + system[3].ToString() + ")");
        WriteLine("=====================================");
        
    }
}

This would produce:

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

Again, notice that the ShowPoints() method receives an array without values but it changes it. When this method 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 static System.Console;

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

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

        WriteLine("In ShowPoints() - Points Coordinates");
        WriteLine("P(" + pts[0].ToString() + ", " + pts[1].ToString() + ")");
        WriteLine("Q(" + pts[2].ToString() + ", " + pts[3].ToString() + ")");
    }
}

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

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

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

        coordinates.ShowPoints(system);
        WriteLine("-------------------------------------");

        WriteLine("Back in Main() - Points Coordinates");
        WriteLine("P(" + system[0].ToString() + ", " + system[1].ToString() + ")");
        WriteLine("Q(" + system[2].ToString() + ", " + system[3].ToString() + ")");
        WriteLine("=====================================");
        
    }
}

This would produce:

In Main() - Points Coordinates
P(-10, 0)
Q(5, -2)
-------------------------------------
Entering ShowPoints() - Points Coordinates
P(-10, 0)
Q(5, -2)
In ShowPoints() - Points Coordinates
P(2, -4)
Q(6, 3)
-------------------------------------
Back 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 static System.Console;

public class CoordinateSystem
{
    public void ShowPoints(ref int[] pts)
    {
        WriteLine("Entering ShowPoints() - Points Coordinates");
        WriteLine("P(" + pts[0].ToString() + ", " + pts[1].ToString() + ")");
        WriteLine("Q(" + pts[2].ToString() + ", " + pts[3].ToString() + ")");

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

        WriteLine("In ShowPoints() - Points Coordinates");
        WriteLine("P(" + pts[0].ToString() + ", " + pts[1].ToString() + ")");
        WriteLine("Q(" + pts[2].ToString() + ", " + pts[3].ToString() + ")");
    }
}

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

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

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

        coordinates.ShowPoints(ref system);
        WriteLine("-------------------------------------");

        WriteLine("Back in Main() - Points Coordinates");
        WriteLine("P(" + system[0].ToString() + ", " + system[1].ToString() + ")");
        WriteLine("Q(" + system[2].ToString() + ", " + system[3].ToString() + ")");
        WriteLine("=====================================");
        
    }
}

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 uses one or more arrays as parameter(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 method 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 static System.Console;

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

        WriteLine("In ShowPoints() - Points Coordinates");
        WriteLine("P(" + pts[0].ToString() + ", " + pts[1].ToString() + ")");
        WriteLine("Q(" + pts[2].ToString() + ", " + pts[3].ToString() + ")");
    }
}

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

        coordinates.ShowPoints(out system);
        WriteLine("-------------------------------------");

        WriteLine("Back in Main() - Points Coordinates");
        WriteLine("P(" + system[0].ToString() + ", " + system[1].ToString() + ")");
        WriteLine("Q(" + system[2].ToString() + ", " + system[3].ToString() + ")");
        WriteLine("=====================================");
        
    }
}

This would produce:

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

Passing a Varied Number of Parameters

When you pass an array as argument or 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 arguments 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 the number of 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 static System.Console;

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

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

public class Exercise
{
    public static int Main()
    {
        int[] system = new int[4];
        CoordinateSystem 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 22446688;
    }
}

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.

The Main Function of an Application

Introduction to Command Line Arguments

An executable application, such as those we have created so far, except in the lesson about libraries, allow a user to provide information or additional information when the program executes. Such additional is provided as an array of strings. The array is passed as an argument to the Main() function. This can be done as follows:

public class Exercise
{
    static void Main(string[] arguments)
    {
         
    }
}

As we have mentioned many times in the previousl lessons, if you create a method that uses a parameter, you don't have to use the parameter in the method. If you have no use for it, you can simply ignore. This is also true for the Main() method: You can create it with a string array parameter but, if you want, you don't have to use the argument in the body of the method.

A Microsoft Visual Studio Console Application

Microsoft Visual Studio provides a template to create a console application. To use it, display the New Project dialog box. In the middle list, click Console App (.NET Framework). Accept or change the name of the project and click OK. Microsoft Visual Studio would create the project, add a primary class to it, and create a Main() method in that class. It also put a string parameter in the parentheses of the Main() method. Other thant that, you can use that primary class as we have done so far.

Getting the Command Line Arguments

To assist you with knowing the command line passed to an application, the Environment class provides a method named  GetCommentLineArgs(). Its syntax is:

public static string[] GetCommandLineArgs();

As you can see, this method returns a string array that represents the arguments to the command line.

Getting the Command Line Information

To assist you with getting the information about the command line of an application, the Environment class provides a property named CommandLine. Here is an example of accessing it:

using System;

public class Exercise
{
    static void Main()
    {
        Console.WriteLine("Command Line: {0}", Environment.CommandLine);

        Environment.Exit(0);
    }
}

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2019, FunctionX Next