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

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

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 variants), bool, float, double, decimal, string, etc). It can also be the name of a class, or structure, or record, etc, 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:

double[] numbers = new double[5];

Here are examples using the var or the dynamic keyword:

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, or an object, 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. You have many options.

Initializing Each Item

An array is primarily a variable; it is simply meant to carry more than one value. There are many 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:

double[] 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:

double[] 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:

double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

Since the data type on the left side of the assignment operator indicates the types of the values of the array, you can omit the data type on the right side. Here is an example:

double[] numbers = new[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

If you use this technique, you must not enter the size of the array in the square brackets. In the above two cases that you leave the square brackets empty, the compiler will figure out the number of items.

Since the declaration on the left side of the assignment operator indicates that you are creating an array, you don't need to indicate it on the right side of the assignment operator. Here is an example:

double[] numbers =  { 12.44, 525.38, 6.28, 2448.32, 632.04 };

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:

double[] 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:

double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

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

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 exception.

Practical LearningPractical Learning: Accessing the Items of an Array

  1. Change the code as follows:
    using static System.Console;
    
    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 them 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:

var singles = new[] { 1244F, 525.38F, 6.28F, 2448.32F, 632.04F };
var doubles = new[] { 3.212D, 3047.098D, 732074.02, 18342.3579 };

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

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:

int GetIndex()
{
    return 2;
}

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:

double area = 97394.2204D;
double distance = 982.84D;
double level = 27D;
double quantity = 237957.704D;

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

Array Members from Constants

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

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:

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:

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:

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:

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:

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:

int GetIndex()
{
    return 2;
}

double GetDistance()
{
    return 632.04;
}

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:

int GetIndex()
{
    return 2;
}

int SpecifyIndex()
{
    return 3;
}

double GetDistance()
{
    return 632.04;
}

double SpecifyValue()
{
    return 2448.32;
}

double[] numbers = new double[5];

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

Arrays and Functions

Introduction

An array is primarily is a type in its own right. As such, it can be used in the various ways we have dealt with data types so far. The main issue to keep in mind is that the type of an array is a series of values.

Returning an Array from a Function

Like a normal variable, an array can be returned from a function. This means that the function would return a variable that carries various values. To start, when creating the function, you must specify its data type as an array. That is, write the desired data type of the array followed by empty square brackets. Here is an example:

int[] Initialize()
{

}

In the body of the function, perform any operation or processing your want. Before the closing curly bracket, you must return a value that holds an array. As one way you can do this, in the body of the function, you can create an initialize an array variable, then return that variable. Here is an example:

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

	return coords;
}

If you know the array you want to return and you don't need to use it many time, you don't have to declare a variable for it. You can return it directly on the function. This can be done as follows:

string[] CreateWaterVehicles()
{
    return new string[] { "canoe", "boat", "ship", "submarine" };
}

You can omit the data type. This can be done as follows:

string[] CreateWaterVehicles()
{
    return new[] { "canoe", "boat", "ship", "submarine" };
}

In the function, you can create a conditional statement that specifies the returned array based on a condition. Here is an example:

string[] GetPronouns(int nbr)
{
    string[] pronouns = new string[6];

    if (nbr == 1)
        pronouns = new string[] { "I", "you", "he/she", "we", "you", "they" };
    else if (nbr == 2)
        pronouns = new string[] { "me", "you", "him/her", "us", "you", "them" };
    else if (nbr == 3)
        pronouns = new string[] { "myself", "yourself", "himself/herself", "ourselves", "yourselves", "themselves" };
    else
        pronouns = new string[] { "unknown", "unknown", "unknown", "unknown", "unknown", "unknown" };

    return pronouns;
}

Once again, remember that you use a variable if you are planning to use a value many times. Otherwise, you may not need a variable. Here is an example:

string[] GetPronouns(int nbr)
{
    if (nbr == 1)
        return new string[] { "I", "you", "he/she", "we", "you", "they" };
    else if (nbr == 2)
        return new string[] { "me", "you", "him/her", "us", "you", "them" };
    else if (nbr == 3)
        return new string[] { "myself", "yourself", "himself/herself", "ourselves", "yourselves", "themselves" };
    else
        return new string[] { "unknown", "unknown", "unknown", "unknown", "unknown", "unknown" };
}

Getting the Returned Array of a Function

When a function returns an array, that function can be assigned to an array variable declared locally where you want to use it. Remember to initialize a variable with such a function only if the variable is an array. Here is an example:

int[] system = new int[4];

system = Initialize();

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

    return coords;
}

Once you have the returned array from the function, you can use that array normally. Here is an example:

int[] system = new int[4];

system = Initialize();

Console.WriteLine($"Number: {system[0]}");
Console.WriteLine($"Number: {system[1]}");
Console.WriteLine($"Number: {system[2]}");
Console.WriteLine($"Number: {system[3]}");
Console.WriteLine("====================");
        
int[] Initialize()
{
    var coords = new int[] { 12, 5, 625, -2 };

    return coords;
}

This would produce:

Number: 12
Number: 5
Number: 625
Number: -2
====================

Press any key to close this window . . .

The function could also be called as follows:

int[] system = Initialize();

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

    return coords;
}

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

int[] system = Initialize();

int[] Initialize()
{
    var 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 function, provide the data type, empty square brackets, and the name of the argument. Here is an example:

void ShowPoints(int[] points)
{
}

When an array has been passed to a function, it can be used in the body of the function 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:

using static System.Console;

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

    return coords;
}

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

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

int[] geos = Initialize();

CreateCoordinate(geos);

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

    return coords;
}

void CreateCoordinate(int[] pts)
{
    Console.WriteLine("P(" + pts[0] + ", " + pts[1] + "), Q(" + pts[2] + ", " + pts[1] + ")");
}

This would produce:

P(12, 5), Q(625, 5)

Press any key to close this window . . .

The Main() Function of an Application

As we have seen so far in all our projects, every (console) 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 C# Console Application in Microsoft Visual Studio, the generated project would have a Main() function that has a string[] array. Here is the content of the code document created from the New Project dialog box:

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

As is the case for variables of primitive types, you can pass an array by reference. To do that, in the parentheses of the function, before the ref keyword. This can be done as follows:

void Initialize(ref int[] coords)
{

}

When you call such a function, precede the argument with the ref keyword. This can be done as follows:

int[] points = new int[4];
        
Initialize(ref points);

void Initialize(ref int[] coords)
{

}

As is the case for values of primitive types, if you pass an array by reference, the function can modify the array. If that happens, when the function exits, the changes made on the array are kept. Here is an example:

int[] points = new int[4];
        
Initialize(ref points);

CreateCoordinate(points);

Console.WriteLine("======================================");
        
void Initialize(ref int[] coords)
{
    coords = new int[] { 6, 3, -5, 0 };
}

void CreateCoordinate(int[] pts)
{
    Console.WriteLine("Points Coordinates: P(" + pts[0] + ", " + pts[1] + "), Q(" + pts[2] + ", " + pts[1] + ")");
}

This would produce:

Points Coordinates: P(6, 3), Q(-5, 3)
======================================

Press any key to close this window . . .

Instead of just one, you can create a function that receives more than one array and you can create a function that receives a combination of one or more arrays and one or more regular arguments. You can also create a function 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 function 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 function 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 function that receives the out array must initialize it before exiting. Here is an example:

int[] points = new int[4];
        
Initialize(out points);

CreateCoordinate(points);

Console.WriteLine("======================================");

void Initialize(out int[] coords)
{
    coords = new int[] { 1, 4, 2, -4 };
}

void CreateCoordinate(int[] pts)
{
    Console.WriteLine("Points Coordinates: 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 function, you must pass the exact number of arguments. That is, you must know the number of arguments the function will process. An alternative to this is to pass only one array as argument. Then, when, or every time, you call the function, you can pass any number of values you want. That is, at one time you can call the function and pass 2 values. At another time, you can call the same function but pass more arguments to it.

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

void ShowPoints(params int[] points)
{

}

As mentioned already, when calling the function, you can pass the number of arguments you want. It's important to know that the function 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 function to know the number of arguments it received. Because this information is not known to the function, the Array class provides a property named Length that holds the size of the array. Here are examples:

void Describe(params int[] pts)
{
    int dimension = pts.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.");
    }
}

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

Console.WriteLine("Points Coordinates");
Console.WriteLine("======================================================");

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

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

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

// The method is called with three arguments
Console.WriteLine("Coordinates: -4, 3, 1");
Describe(-4, 3, 1);
Console.WriteLine("======================================================");
        
void Describe(params int[] pts)
{
    int dimension = pts.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.");
    }
}

This would produce:

Points Coordinates
======================================================
Coordinate: -6
The point is located on a line.
------------------------------------------------------
The point is located on a multi-dimensional system.
Coordinates: 2, 2, 5, -3
------------------------------------------------------
Coordinates: 2, 5
The point is located on a Cartesian coordinate system.
------------------------------------------------------
Coordinates: -4, 3, 1
The point is located on a 3-D coordinate system.
======================================================

Press any key to close this window . . .

A Global Array

Introduction

So far, when we needed an array, we created it in the body or the Main() function or the body of any function. Such an array can be used only in the body of the function in which it was created. Sometimes, you want to share an array among many functions. To make this possible, you can create an array outside any function. Such an array is referred to as a global array. Here is an example:

string[] degrees = new string[3];

Obviously before using an array, you must initialize it. As seen in our introductions, you can initialize an array when you create it. This is also valid for global arrays. Here is an example:

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:

 int[] Points = new int[4];

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

string[] degrees = new string[3] { "Associate", "Bachelor", "Master" };

As an alternative, you can initialize the array in the body of the Main() function or in the body of any function of your choice. Here is an example:

string[] housePlans = new string[6];

void Initialize()
{
    housePlans = new[] { "Country", "Cottage", "Bungalow",
                             "Colonial", "Cabin", "Contemporary" };
}

Presenting the Array

After an array has been created outside any function, it can be used. Here is an example:

string[] housePlans;

Initialize();

Console.WriteLine($"House Style: {housePlans[0]}");
Console.WriteLine($"House Style: {housePlans[1]}");
Console.WriteLine($"House Style: {housePlans[2]}");
Console.WriteLine($"House Style: {housePlans[3]}");
Console.WriteLine($"House Style: {housePlans[4]}");
Console.WriteLine($"House Style: {housePlans[5]}");
Console.WriteLine("==========================");

void Initialize()
{
    housePlans = new[] { "Country", "Cottage", "Bungalow",
                         "Colonial", "Cabin", "Contemporary" };
}

This produce:

House Style: Country
House Style: Cottage
House Style: Bungalow
House Style: Colonial
House Style: Cabin
House Style: Contemporary
==========================

Press any key to close this window . . .

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2022, FunctionX Monday 11 October 2021 Next