Home

Introduction to Arrays

A Series of Similar Items

Introduction to Lists

A list is a group of items. Normally, the items should be of the same type such as a group of people, a group of house, a group of countries, etc. There are various ways you can programmatically create and manage a list.

Introduction to Arrays

So far, to use a series of items, we were declaring a variable for each of them. If the list was made of numbers, we would declare variables for such numbers as follows:

public class Program
{
    public static void Main()
    {
        double number1 = 12.44
        double number2 = 525.38;
        double number3 = 6.28;
        double number4 = 2448.32;
        double number5 = 632.04;
    }
}

Instead of using individual variables that share the same characteristics, you can group the values in one entity and use that entity as one unit or a regular variable. This group is called an array. Therefore, an array is a group of items with the following characteristics:

Practical LearningPractical Learning: Introducing Arrays

  1. Start Microsoft Visual Studio
  2. On the Visual Studio 2019 dialog box, click Create a New Application
  3. In the Create a New Project dialog box, in the list of projects templaates, click Console App (.NET Framework)
  4. Click Next
  5. Change the name of the project to CountriesStatistics1
  6. Click Create

Array Creation

Before creating an array, you must first specify the type its items will be made of. This is because each item of the group will occupy its own memory space, just like any of the variables we have used so far.

After deciding about the type of data of each item that makes up the series, you must use a common name to identify them. The name is the name for the variable that all items of the array will use. The name of an array follows the rules of names of variables. In our lessons, since we consider that an array is a group of values, we will name our array variables in plural.

Unlike a regular list that can contain any number of items, an array has a fixed or constant number of items. Therefore, you must specify the number of items that will constitute the array. The number of items of an array is included in square brackets, as in [5].

An array is considered a reference type. Therefore, an array requests its memory using the new operator. Based on this, one of the formulas to create an array is:

data-type[] variable-name = new data-type[number];

Alternatively, you can use the var or the dynamic keyword to create an array. The formulas to use would be:

var variable-name = new data-type[number];
dynamic variable-name = new data-type[number];

In these formulas, the data-type can be one of the types we have used so far (int (or one of its variables), bool, float, double, decimal, string, etc). It can also be the name of a class as we will learn. Like a normal variable, an array must have a name, represented in our formulas as variable-name. The square brackets on the left of the assignment operator are used to let the compiler know that you are creating an array instead of a regular variable. The new operator allows the compiler to reserve memory. The number is used to specify the number of items of the group.

Based on the above formula, here is an example of an array variable:

public class Program
{
    public static void Main()
    {
        double[] numbers = new double[5];
    }
}

Here are examples using the var or the dynamic keyword:

public class Program
{
    public static void Main()
    {
        double[] numbers = new double[5];
	    var distances = new float[8];
    	dynamic values = new int[3];
    }
}

Practical LearningPractical Learning: Creating an Array

Introduction to the Array Class

To support arrays, the .NET Framework provides a class named Array. The Array class is defined in the System namespace. Whenever you create or use an array, it is actually an object of type Array. This class provides various properties and methods that can be used to manage an array.

Initializing an Array

Introduction

When creating an array, you can specify the number of items that make up its group. Each item of the series is referred to as a member or an element or an item of the array. Once the array has been created, each one of its members is initialized with a default value. Most, if not all, of the time, you will need to change the value of each member to a value of your choice. This is referred to as initializing the array.

Initializing Each Item

An array is primarily a variable; it is simply meant to carry more than one value. There are two main techniques you can use to initialize an array. If you have declared an array as done above, to initialize it, you can access each one of its members and assign it a desired but appropriate value.

In algebra, if you create a series of values as X1, X2, X3, X4, and X5, each member of this series can be identified by its subscript number. In this case the subscripts are 1, 2, 3, 4, and 5. This subscript number is also called an index. In the case of an array also, each member can be referred to by an incremental number called an index. A C# array is zero-based. This means that the first member of the array has an index of 0, the second has an index of 1, and so on. In algebra, the series would be represented as X0, X1, X2, X3, and X4.

In C#, the index of a member of an array is written in its own square brackets. This is the notation you would use to locate each member. One of the actions you can take would consist of assigning it a value. Here is an example:

public class Program
{
    public static void Main()
    {
        int numbers = new double[5];

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

Practical LearningPractical Learning: Initializing Each Item of an Array

Initializing an Array of Items

Besides this technique, you can also initialize the array as a whole when declaring it. To do this, on the right side of the declaration, before the closing semi-colon, type the values of the array members between curly brackets and separated by commas. Here is an example:

public class Program
{
    public static void Main()
    {
        int numbers = new double[5] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
    }
}

If you use this second technique, you don't have to specify the number of items in the series. In this case, you can leave the square brackets empty. Here is an example:

public class Program
{
    public static void Main()
    {
        int numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
    }
}

If you leave the square brackets empty, the compiler will figure out the number of items.

Practical LearningPractical Learning: Initializing the Items as an Array

The Length or Size of an Array

We saw that if you declare an array variable but don't initialize it, you must specify the number of elements of the array. This number is passed inside the second pair of square brackets, as a constant integer. Here is an example:

public class Program
{
    public static void Main()
    {
        int[] numbers = new double[5];
    }
}

If the array exists already, to assist you with finding out the number of elements in it, the Array class provides a read-only property named Length:

public int Length { get; }

Therefore, to know the number of items that an array contains, get the value of the Length property.

Introduction to Accessing the Members of an Array

After initializing an array, which means after each of its members has been given a value, you can access a member of the array to get, manipulate or even change its value. To access a member of the array, you use the square brackets as we saw above. As done for normal variables, one of the reasons of accessing a member of an array is to display its value. Here is an example:

using System;

public class Program
{
    public static void Main()
    {
        double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        Console.Write("Number: ");
        Console.WriteLine(numbers[3]);
        Console.WriteLine("===========================");

        return;
    }
}

This would produce:

Number: 2448.32
===========================
Press any key to continue . . .

In the same way, you can access 1, a few or all members of an array.

Remember that, to access a member of an array, pass its index to the square brackets of the variable. If you pass an index higher than the number of items in the array, the compiler will throw an Click event of a button:

Modeling a Picnic Table

Practical LearningPractical Learning: Accessing the Items of an Array

  1. Change the code as follows:
    using static System.Console;
    
    namespace CountriesStatistics1
    {
        class Program
        {
            static void Main()
            {
                string[] states = new string[31];
    
                states[0]  = "Guanajuato          ";  states[1]  = "Tamaulipas          "; states[2]  = "Michoacán           ";
                states[3]  = "Coahuila            ";  states[4]  = "Chihuahua           "; states[5]  = "Baja California Sur ";
                states[6]  = "Nayarit             ";  states[7]  = "Puebla              "; states[8]  = "Oaxaca              ";
                states[9]  = "Morelos             ";  states[10] = "Sonora              "; states[11] = "Aguascalientes      ";
                states[12] = "Baja California     ";  states[13] = "Tabasco             "; states[14] = "Jalisco             ";
                states[15] = "México              ";  states[16] = "Guerrero            "; states[17] = "Colima              ";
                states[18] = "Zacatecas           ";  states[19] = "Sinaloa             "; states[20] = "Campeche            ";
                states[21] = "Quintana Roo        ";  states[22] = "Nuevo León          "; states[23] = "Hidalgo             ";
                states[24] = "Tlaxcala            ";  states[25] = "Yucatán             "; states[26] = "Querétaro           ";
                states[27] = "Veracruz            ";  states[28] = "San Luis Potosí     "; states[29] = "Durango             ";
                states[30] = "Chiapas             ";
    
                string[] capitals = new string[] { "Guanajuato                ", "Ciudad Victoria           ", "Morelia                   ",
                                                   "Saltillo                  ", "Chihuahua                 ", "La Paz                    ",
                                                   "Tepic                     ", "Puebla de Zaragoza        ", "Oaxaca de Juárez          ",
                                                   "Cuernavaca                ", "Hermosillo                ", "Aguascalientes            ",
                                                   "Mexicali                  ", "Villahermosa              ", "Guadalajara               ",
                                                   "Toluca de Lerdo           ", "Chilpancingo de los Bravo ", "Colima                    ",
                                                   "Zacatecas                 ", "Culiacán                  ", "San Francisco de Campeche ",
                                                   "Chetumal                  ", "Monterrey                 ", "Pachuca                   ",
                                                   "Tlaxcala                  ", "Mérida                    ", "Santiago de Querétaro     ",
                                                   "Xalapa                    ", "San Luis Potosí           ", "Victoria de Durango       ",
                                                   "Tuxtla Gutiérrez          "};
                int[] areasSqrKms = new int[]  {   30608,  80175, 58643, 151563, 247455, 73922, 27815, 34290, 93793,   4893,
                                                   179503,  5618, 71446,  24738,  78599, 22357, 63621,  5625, 75539,  57377,
                                                   57924,  42361, 64220,  20846,   3991, 39612, 11684, 71820, 60983, 123451, 73289 };
                int[] areasSqrMiles = new int[] {  11818,  30956, 22642,  58519,  95543, 28541, 10739, 13240, 36214,   1889,
                                                   69306,   2169, 27585,   9551,  30347,  8632, 24564,  2172, 29166,  22153,
                                                   22365,  16356, 24800,   8049,   1541, 15294,  4511, 27730, 23546,  47665, 28297 };
                int[] ordersOfAdmissionToFederation = new int[] {  2, 14,  5, 16, 18, 31, 28,  4,  3, 27,
                                                                  12, 24, 29, 13,  9,  1, 21, 23, 10, 20,
                                                                  25, 30, 15, 26, 22,  8, 11,  7,  6, 17, 19 };
    
                WriteLine("===============================================================================");
                WriteLine("                                                       Area      Order Admission");
                WriteLine("# State Name           Capital                   Sqr Kms Sqr Miles     to Federation");
                WriteLine("-------------------------------------------------------------------------------");
                WriteLine("1  " + states[0]  + " " + capitals[0]  + " " + areasSqrKms[0]  + "  " + areasSqrMiles[0]  + "        " + ordersOfAdmissionToFederation[0]);
                WriteLine("2  " + states[1]  + " " + capitals[1]  + " " + areasSqrKms[1]  + "  " + areasSqrMiles[1]  + "        " + ordersOfAdmissionToFederation[1]);
                WriteLine("3  " + states[2]  + " " + capitals[2]  + " " + areasSqrKms[2]  + "  " + areasSqrMiles[2]  + "        " + ordersOfAdmissionToFederation[2]);
                WriteLine("4  " + states[3]  + " " + capitals[3]  + " " + areasSqrKms[3]  + "  " + areasSqrMiles[3]  + "        " + ordersOfAdmissionToFederation[3]);
                WriteLine("5  " + states[4]  + " " + capitals[4]  + " " + areasSqrKms[4]  + "  " + areasSqrMiles[4]  + "        " + ordersOfAdmissionToFederation[4]);
                WriteLine("6  " + states[5]  + " " + capitals[5]  + " " + areasSqrKms[5]  + "  " + areasSqrMiles[5]  + "        " + ordersOfAdmissionToFederation[5]);
                WriteLine("7  " + states[6]  + " " + capitals[6]  + " " + areasSqrKms[6]  + "  " + areasSqrMiles[6]  + "        " + ordersOfAdmissionToFederation[6]);
                WriteLine("8  " + states[7]  + " " + capitals[7]  + " " + areasSqrKms[7]  + "  " + areasSqrMiles[7]  + "        " + ordersOfAdmissionToFederation[7]);
                WriteLine("9  " + states[8]  + " " + capitals[8]  + " " + areasSqrKms[8]  + "  " + areasSqrMiles[8]  + "        " + ordersOfAdmissionToFederation[8]);
                WriteLine("10 " + states[9]  + " " + capitals[9]  + " " + areasSqrKms[9]  + "  " + areasSqrMiles[9]  + "        " + ordersOfAdmissionToFederation[9]);
                WriteLine("11 " + states[10] + " " + capitals[10] + " " + areasSqrKms[10] + "  " + areasSqrMiles[10] + "        " + ordersOfAdmissionToFederation[10]);
                WriteLine("12 " + states[11] + " " + capitals[11] + " " + areasSqrKms[11] + "  " + areasSqrMiles[11] + "        " + ordersOfAdmissionToFederation[11]);
                WriteLine("13 " + states[12] + " " + capitals[12] + " " + areasSqrKms[12] + "  " + areasSqrMiles[12] + "        " + ordersOfAdmissionToFederation[12]);
                WriteLine("14 " + states[13] + " " + capitals[13] + " " + areasSqrKms[13] + "  " + areasSqrMiles[13] + "        " + ordersOfAdmissionToFederation[13]);
                WriteLine("15 " + states[14] + " " + capitals[14] + " " + areasSqrKms[14] + "  " + areasSqrMiles[14] + "        " + ordersOfAdmissionToFederation[14]);
                WriteLine("16 " + states[15] + " " + capitals[15] + " " + areasSqrKms[15] + "  " + areasSqrMiles[15] + "        " + ordersOfAdmissionToFederation[15]);
                WriteLine("17 " + states[16] + " " + capitals[16] + " " + areasSqrKms[16] + "  " + areasSqrMiles[16] + "        " + ordersOfAdmissionToFederation[16]);
                WriteLine("18 " + states[17] + " " + capitals[17] + " " + areasSqrKms[17] + "  " + areasSqrMiles[17] + "        " + ordersOfAdmissionToFederation[17]);
                WriteLine("19 " + states[18] + " " + capitals[18] + " " + areasSqrKms[18] + "  " + areasSqrMiles[18] + "        " + ordersOfAdmissionToFederation[18]);
                WriteLine("20 " + states[19] + " " + capitals[19] + " " + areasSqrKms[19] + "  " + areasSqrMiles[19] + "        " + ordersOfAdmissionToFederation[19]);
                WriteLine("21 " + states[20] + " " + capitals[20] + " " + areasSqrKms[20] + "  " + areasSqrMiles[20] + "        " + ordersOfAdmissionToFederation[20]);
                WriteLine("22 " + states[21] + " " + capitals[21] + " " + areasSqrKms[21] + "  " + areasSqrMiles[21] + "        " + ordersOfAdmissionToFederation[21]);
                WriteLine("23 " + states[22] + " " + capitals[22] + " " + areasSqrKms[22] + "  " + areasSqrMiles[22] + "        " + ordersOfAdmissionToFederation[22]);
                WriteLine("24 " + states[23] + " " + capitals[23] + " " + areasSqrKms[23] + "  " + areasSqrMiles[23] + "        " + ordersOfAdmissionToFederation[23]);
                WriteLine("25 " + states[24] + " " + capitals[24] + " " + areasSqrKms[24] + "  " + areasSqrMiles[24] + "        " + ordersOfAdmissionToFederation[24]);
                WriteLine("26 " + states[25] + " " + capitals[25] + " " + areasSqrKms[25] + "  " + areasSqrMiles[25] + "        " + ordersOfAdmissionToFederation[25]);
                WriteLine("27 " + states[26] + " " + capitals[26] + " " + areasSqrKms[26] + "  " + areasSqrMiles[26] + "        " + ordersOfAdmissionToFederation[26]);
                WriteLine("28 " + states[27] + " " + capitals[27] + " " + areasSqrKms[27] + "  " + areasSqrMiles[27] + "        " + ordersOfAdmissionToFederation[27]);
                WriteLine("29 " + states[28] + " " + capitals[28] + " " + areasSqrKms[28] + "  " + areasSqrMiles[28] + "        " + ordersOfAdmissionToFederation[28]);
                WriteLine("30 " + states[29] + " " + capitals[29] + " " + areasSqrKms[29] + "  " + areasSqrMiles[29] + "        " + ordersOfAdmissionToFederation[29]);
                WriteLine("31 " + states[30] + " " + capitals[30] + " " + areasSqrKms[30] + "  " + areasSqrMiles[30] + "        " + ordersOfAdmissionToFederation[30]);
                WriteLine("===============================================================================");
            }
        }
    }
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging
    ===============================================================================
                                                           Area      Order Admission
    
    # State Name           Capital                   Sqr Kms Sqr Miles     to Federa
    tion
    -------------------------------------------------------------------------------
    1  Guanajuato           Guanajuato                 30608  11818        2
    2  Tamaulipas           Ciudad Victoria            80175  30956        14
    3  Michoacán            Morelia                    58643  22642        5
    4  Coahuila             Saltillo                   151563  58519        16
    5  Chihuahua            Chihuahua                  247455  95543        18
    6  Baja California Sur  La Paz                     73922  28541        31
    7  Nayarit              Tepic                      27815  10739        28
    8  Puebla               Puebla de Zaragoza         34290  13240        4
    9  Oaxaca               Oaxaca de Juárez           93793  36214        3
    10 Morelos              Cuernavaca                 4893  1889        27
    11 Sonora               Hermosillo                 179503  69306        12
    12 Aguascalientes       Aguascalientes             5618  2169        24
    13 Baja California      Mexicali                   71446  27585        29
    14 Tabasco              Villahermosa               24738  9551        13
    15 Jalisco              Guadalajara                78599  30347        9
    16 México               Toluca de Lerdo            22357  8632        1
    17 Guerrero             Chilpancingo de los Bravo  63621  24564        21
    18 Colima               Colima                     5625  2172        23
    19 Zacatecas            Zacatecas                  75539  29166        10
    20 Sinaloa              Culiacán                   57377  22153        20
    21 Campeche             San Francisco de Campeche  57924  22365        25
    22 Quintana Roo         Chetumal                   42361  16356        30
    23 Nuevo León           Monterrey                  64220  24800        15
    24 Hidalgo              Pachuca                    20846  8049        26
    25 Tlaxcala             Tlaxcala                   3991  1541        22
    26 Yucatán              Mérida                     39612  15294        8
    27 Querétaro            Santiago de Querétaro      11684  4511        11
    28 Veracruz             Xalapa                     71820  27730        7
    29 San Luis Potosí      San Luis Potosí            60983  23546        6
    30 Durango              Victoria de Durango        123451  47665        17
    31 Chiapas              Tuxtla Gutiérrez           73289  28297        19
    ===============================================================================
    Press any key to continue . . .
  3. Press Enter to close the DOS window and return to your programming environment

Anonymous Arrays

Introduction

In previous sections, when creating an array, we were specifying its type. As seen in our introduction to variables, a good feature of the var or the dynamic keyword is that, when using it to declare and initialize a variable, you ask the compiler to figure out what type of data the variable is holding. This concept is also valid for an array.

An anonymous array is an array variable whose type is left to the compiler to determine, based on the types of values of the array.

Creating an Anonymous Array

As done for variables so far, when creating an array, you can use the var or the dynamic keyword, initialize the array, but not specify its data type. The formula to use is:

var array-name = new[] { initialization };

The formula is almost similar to that of a normal array, with keywords and operators you are already familiar with. The array-name is the name of the variable. Notice that the new keyword is directly followed by the square brackets. In the curly brackets, you must initialize the array by providing the necessary values. For the compiler to be able to figure out the type and amount of memory to allocate for the array variable, all values must be of the same type or the same category:

Accessing the Members of an Anonymous Array

After creating an anonymous array, you can access each member using its index. Here are two examples:

using static System.Console;

public class Program
{
    public static void Main()
    {
        var singles = new[] { 1244F, 525.38F, 6.28F, 2448.32F, 632.04F };
        var doubles = new[] { 3.212D, 3047.098D, 732074.02, 18342.3579 };

        Write("Number: ");
        WriteLine(singles[2]);
        Write("Number: ");
        WriteLine(doubles[0]);
        WriteLine("====================");

        return;
    }
}

This would produce:

Number: 6.28
Number: 3.212
====================
Press any key to continue . . .

Techniques of Initializing an Array

A Return Value as an Index

When accessing a member of an array using its index, the value between square brackets must be known. Most of the time, it is a constant, but this is not always the case. The rule is that, at the time you open the square brackets, the value must be known, even if it is not a constant. For example, the value can be returned from a function/method. Here is an example:

namespace Exercises
{
    public class Exercise
    {
        int GetIndex()
        {
            return 2;
        }

        public void GetNumbers()
        {
            double[] numbers = new double[5];

            numbers[0] = 12.44;
            numbers[1] = 525.38;
            numbers[GetIndex()] = 6.28;
            numbers[3] = 2448.32;
            numbers[4] = 632.04;
        }
    }
}

Variables as Members of an Array

We have initialized our arrays so far with values we specified directly in the curly brackets. If you have declared and initialized some variables of the same type, you can use them to initialize an array. You use those values in place of the members of the array. Here is an example:

public class Program
{
    public static void Main()
    {
        double area = 97394.2204D;
        double distance = 982.84D;
        double level = 27D;
        double quantity = 237957.704D;

        double[] measures = new double[] { area, distance, level, quantity };
        
        return;
    }
}

Array Members from Constants

The values of the members of an array can come from constant variables. Here is an example:

public class Program
{
    public static void Main()
    {
        const double PI = 3.141592653;
        double squareRootOf2 = 1.414D;
        double e = 2.718D;
        const double radiusOfEarth = 6370; // km
        double ln2 = 0.6931;

        double[] measures = new double[] { PI, squareRootOf2, e, radiusOfEarth, ln2 };
    }
}

Expressions as Members of an Array

The values of the members of an array can come from calculations. A calculation can come from an initialized variable or made locally in the curly brackets. Here is an example:

public class Program
{
    public static void Main()
    {
        const double densityOfWater = 1000; // kg/m3 ;
        double massOfEarth = 5.98 * 10e24; // kg
        double earthMoonDistance = 2.39 * 10e5; // miles

        double[] Measures = new double[]
        {
            densityOfWater, 9.30 * 10.7, massOfEarth, earthMoonDistance
        };
    }
}

The rule to follow is that, at the time the array is created, the compiler must be able to know exactly the value of each member of the array, no guessing.

Hexadecimal Values as Members of an Array

If the members of an array are integers, you can use decimals, hexadecimal values, or a combination of both. Here is an example:

public class Program
{
    public static void Main()
    {
        int red = 0xFF0000;
	    int someColor = 0x800000;

	    int[] colors = new int[] { 2510, red, 818203, someColor, 0xF28AC };
    }
}

Boolean Values as Members of an Array

The members of an array can hold Boolean values. Here is an example:

public class Exercise
{
    static int Main()
    {
        bool[] fullTimeStudents = new bool[] { true, true, true, false, true, false };
    }
}

You can also use the var or the dynamic keyword to declare the variable, as long as each element can be evaluated to true or false. Here is an example:

public class Exercise
{
    static int Main()
    {
        var qualifications = new[] { true, true, false, true, false };
    }
}

Each value of a Boolean array must be evaluated to true or false. This means that you can use variables or expressions as members of the array. Here is an example:

public class Exercise
{
    static int Main()
    {
        bool[] conparisons = new bool[] { 25 < 10, house1Value == house2Value, true };
    }
}

A Returned Value as a Member of an Array

The value of a member of an array can be the returned value of a method. Here is an example:

namespace Exercises
{
    public class Exercise
    {
        int GetIndex()
        {
            return 2;
        }

        double GetDistance()
        {
            return 632.04;
        }

        public void GetNumbers()
        {
            double[] numbers = new double[5];

            numbers[0] = 12.44;
            numbers[1] = 525.38;
            numbers[GetIndex()] = 6.28;
            numbers[3] = 2448.32;
            numbers[4] = GetDistance();
        }
    }
}

As a result, both the index and the value can come from methods. Here is an example:

namespace Exercises
{
    public class Exercise
    {
        int GetIndex()
        {
            return 2;
        }

        int SpecifyIndex()
        {
            return 3;
        }

        double GetDistance()
        {
            return 632.04;
        }

        double SpecifyValue()
        {
            return 2448.32;
        }

        public void GetNumbers()
        {
            double[] numbers = new double[5];

            numbers[0] = 12.44;
            numbers[1] = 525.38;
            numbers[GetIndex()] = 6.28;
            numbers[SpecifyIndex()] = SpecifyValue();
            numbers[4] = GetDistance();
        }
    }
}

An Array of a Primitive Type 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
{
	public  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
{
 	public  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];
    }
}

You can initialize an array 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
{
    public 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;

namespace Exercises
{
    public class Exercise
    {
        public static void Main()
        {
            CoordinateSystem cs = new CoordinateSystem();

            WriteLine("Coordinate System");
            WriteLine("---------------------------------------");
            Write("Points Coordinates: P(");
            Write(cs.points[0]);
            Write(", ");
            Write(cs.points[1]);
            Write("), Q(");
            Write(cs.points[2]);
            Write(", ");
            Write(cs.points[3]);
            WriteLine(").");
            WriteLine("=======================================");
        }
    }
}

public class CoordinateSystem
{
    public int[] points;

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

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

This produce:

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

Arrays and Methods

Introduction

Because 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 represented by the name of its variable.

You can create a method that uses an array as parameter and return another array.

To create 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:

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;
    }
}

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

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

            system = coordinates.Initialize();
        }
    }
}

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

        return coords;
    }
}

The method could also be called as follows:

namespace Exercises
{
    public class Exercise
    {
        public static void Main()
        {
            CoordinateSystem coordinates = new CoordinateSystem();

            int[] system = coordinates.Initialize();
        }
    }
}

You can also declare the variable using either the var or the dynamic keyword. Those keywords don't need square brackets. Here are examples:

public class Program
{
    public static void Main()
    {
        CoordinateSystem coordinates = new CoordinateSystem();

        var coord = coordinates.Initialize();
        dynamic point = coordinates.Initialize();

        return;
    }
}

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

        return coords;
    }
}

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, some empty square brackets, and the name of the argument. Here is an example:

public class Exercise
{
    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 would 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 string Message;

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

        return coords;
    }

    public void CreateCoordinate(int[] pts)
    {
        Message = "P(" + pts[0] + ", " + pts[1] + "), Q(" + pts[2] + ", " + pts[1] + ")";
    }
}

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

public class Program
{
    public static void Main()
    {
        CoordinateSystem coordinates = new CoordinateSystem();

        int[] points = coordinates.Initialize();
        coordinates.CreateCoordinate(points);

        Write("Points: ");
        WriteLine(coordinates.Message);
        WriteLine("============================");

        return;
    }
}

public class CoordinateSystem
{
    public string Message;

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

        return coords;
    }

    public void CreateCoordinate(int[] pts)
    {
        Message = "P(" + pts[0] + ", " + pts[1] + "), Q(" + pts[2] + ", " + pts[1] + ")";
    }
}

This would produce:

Points: P(12, 5), Q(-2, 5)
============================
Press any key to continue . . .

The Main() Function of an Application

As we have seen so far in all our projects, every (console and Windows Forms) application must have a function named Main. That function as an entry point to an application. As such, you can use that function to check the primary settings of your application. To make this possible, the C# language allows you to pass a string array to the Main() function. This is done as follows:

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

In fact, if you create a Console App (.NET Framework) or Console app (.NET Core) in Microsoft Visual Studio, the generaterd project would have a Main() function that has a string[] array. Here is the content of the code document created the New Project dialog box:

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

As mentionned so far about arguments, you can use or ignore the argument of the Main() function. If you ignore that argument, there will not be any positive or never impact to your application. Otherwise, when the user executes your application, you can get and process the argument of the Main() function. Because that argument is an array, it can contain any number of values. Each can be accessed by its position.

Other Techniques of Passing Arrays as Arguments

Passing an Array By Reference

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:

public class CoordinateSystem
{
    public string Message;

    public void CreateCoordinate(int[] pts)
    {
        pts = new int[] { 6, 3, -5, 0 };

        Message = "P(" + pts[0] + ", " + pts[1] + "), Q(" + pts[2] + ", " + pts[1] + ")";
    }
}

When you call such a method, pass an array to it. Here is an example:

using static System.Console;

public class Program
{
    public static void Main(string[] args)
    {
        CoordinateSystem coordinates = new CoordinateSystem();

        int[] points = new int[4];

        coordinates.CreateCoordinate(points);

        WriteLine("Points Coordinates");
        WriteLine(coordinates.Message);
        WriteLine("============================");

        return;
    }
}

public class CoordinateSystem
{
    public string Message;

    public void CreateCoordinate(int[] pts)
    {
        pts = new int[] { 6, 3, -5, 0 };

        Message = "P(" + pts[0] + ", " + pts[1] + "), Q(" + pts[2] + ", " + pts[1] + ")";
    }
}

This would produce:

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

As aresult, 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 as seen above.

To enforce the concept of passing an array by reference, you can accompany the argument with the ref keyword. You can do this when defining the method. Here is an example:

public class CoordinateSystem
{
    public string Message;

    public void CreateCoordinate(ref int[] pts)
    {
        pts = new int[] { 1, 4, 2, -4 };

        Message = "P(" + pts[0] + ", " + pts[1] + "), Q(" + pts[2] + ", " + pts[1] + ")";
    }
}

You must also use the ref keyword when calling the method. Here is an example:

using static System.Console;

public class Program
{
    public static void Main(string[] args)
    {
        CoordinateSystem coordinates = new CoordinateSystem();

        int[] points = new int[4];

        coordinates.CreateCoordinate(ref points);

        WriteLine("Points Coordinates");
        WriteLine(coordinates.Message);
        WriteLine("============================");

        return;
    }
}

public class CoordinateSystem
{
    public string Message;

    public void CreateCoordinate(ref int[] pts)
    {
        pts = new int[] { 1, 4, 2, -4 };

        Message = "P(" + pts[0] + ", " + pts[1] + "), Q(" + pts[2] + ", " + pts[1] + ")";
    }
}

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 function or 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 Program
{
    public static void Main(string[] args)
    {
        CoordinateSystem coordinates = new CoordinateSystem();

        int[] points = new int[4];

        coordinates.CreateCoordinate(out points);

        WriteLine("Points Coordinates");
        WriteLine(coordinates.Message);
        WriteLine("============================");

        return;
    }
}

public class CoordinateSystem
{
    public string Message;

    public void CreateCoordinate(out int[] pts)
    {
        pts = new int[] { 1, 4, 2, -4 };

        Message = "P(" + pts[0] + ", " + pts[1] + "), Q(" + pts[2] + ", " + pts[1] + ")";
    }
} int[] pts)
    {
        pts = new int[] { 12, 5, -2, -2 };

        Message = "P(" + pts[0] + ", " + pts[1] + "), Q(" + pts[2] + ", " + pts[1] + ")";
    }
}

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

public class CoordinateSystem
{
    public string Message;

    public void Describe(params int[] pts)
    {
        int dimension = pts.Length;

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

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

using static System.Console;

public class Program
{
    public static void Main(string[] args)
    {
        int[] system = new int[4];
        CoordinateSystem coordinates = new CoordinateSystem();
        
        WriteLine("Points Coordinates");
        WriteLine("======================================================");

        // The method is called with one argument
        coordinates.Describe(-6);
        WriteLine("Coordinate: -6");
        WriteLine(coordinates.Message);
        WriteLine("------------------------------------------------------");

        // The method is called with 4 arguments
        coordinates.Describe(2, 2, 5, -3);
        WriteLine("Coordinates: 2, 2, 5, -3");
        WriteLine(coordinates.Message);
        WriteLine("------------------------------------------------------");

        // The method is called with two arguments
        WriteLine("Coordinates: 2, 5");
        coordinates.Describe(2, 5);
        WriteLine(coordinates.Message);
        WriteLine("------------------------------------------------------");

        // The method is called with three arguments
        WriteLine("Coordinates: -4, 3, 1");
        coordinates.Describe(-4, 3, 1);
        WriteLine(coordinates.Message);
        WriteLine("======================================================");

        return;
    }
}

public class CoordinateSystem
{
    public string Message;

    public void Describe(params int[] pts)
    {
        int dimension = pts.Length;

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

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2020, FunctionX Next