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:

• All items are of the same type. They could all be numbers. They could all be strings. They could all be objects of the same class. If you mix items of different types, you would receive an error
• The number of items (called the length) of the array is known and is fixed. This means that, after the array has been created, you cannot add new elements to it (this is the general rule of arrays as used in C, C++, and most languages; the .NET Framework provides a way to expand/increase an array but, by definition, an array has a fixed number of items)
• Each item occupies a specific position known as its index (the index of the item)
• An array is mutable. This means that, at any time, you can change the value of any element in the array, based on the index of that element
• The positions (indexes) of the items start at 0 up to the length - 1 Practical Learning: Introducing Arrays

• Start Microsoft Visual Studio and create a C# Console Application (that supports .NET 5.0) named CountriesStatistics1

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 .

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

Here are examples using the var or the dynamic keyword:

```double[] numbers = new double;
var distances = new float;
dynamic values = new int;``` Practical Learning: Creating an Array

• To create an array, change the document as follows:
`string[] states = new string;`

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;

numbers = 12.44;
numbers = 525.38;
numbers = 6.28;
numbers = 2448.32;
numbers = 632.04;``` Practical Learning: Initializing Each Item of an Array

• Change the code as follows:
```string[] states = new string;

states = "Guanajuato"; states = "Tamaulipas";
states = "Michoacán"; states = "Coahuila";
states = "Chihuahua"; states = "Baja California Sur";
states = "Nayarit"; states = "Puebla";
states = "Oaxaca"; states = "Morelos";
states = "Sonora"; states = "Aguascalientes";
states = "Baja California"; states = "Tabasco";
states = "Jalisco"; states = "México";
states = "Guerrero"; states = "Colima";
states = "Zacatecas"; states = "Sinaloa";
states = "Campeche"; states = "Quintana Roo";
states = "Nuevo León"; states = "Hidalgo";
states = "Tlaxcala"; states = "Yucatán";
states = "Querétaro"; states = "Veracruz";
states = "San Luis Potosí"; states = "Durango";
states = "Chiapas";```

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 { 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 Learning: Initializing the Items as an Array

• Change the code as follows:
```string[] states = new string;

states = "Guanajuato"; states = "Tamaulipas";
states = "Michoacán"; states = "Coahuila";
states = "Chihuahua"; states = "Baja California Sur";
states = "Nayarit"; states = "Puebla";
states = "Oaxaca"; states = "Morelos";
states = "Sonora"; states = "Aguascalientes";
states = "Baja California"; states = "Tabasco";
states = "Jalisco"; states = "México";
states = "Guerrero"; states = "Colima";
states = "Zacatecas"; states = "Sinaloa";
states = "Campeche"; states = "Quintana Roo";
states = "Nuevo León"; states = "Hidalgo";
states = "Tlaxcala"; states = "Yucatán";
states = "Querétaro"; states = "Veracruz";
states = "San Luis Potosí"; states = "Durango";
states = "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"};```

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

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);
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 Learning: Accessing the Items of an Array

1. Change the code as follows:
```using static System.Console;

string[] states = new string;

states  = "Guanajuato          ";  states  = "Tamaulipas          "; states  = "Michoacán           ";
states  = "Coahuila            ";  states  = "Chihuahua           "; states  = "Baja California Sur ";
states  = "Nayarit             ";  states  = "Puebla              "; states  = "Oaxaca              ";
states  = "Morelos             ";  states = "Sonora              "; states = "Aguascalientes      ";
states = "Baja California     ";  states = "Tabasco             "; states = "Jalisco             ";
states = "México              ";  states = "Guerrero            "; states = "Colima              ";
states = "Zacatecas           ";  states = "Sinaloa             "; states = "Campeche            ";
states = "Quintana Roo        ";  states = "Nuevo León          "; states = "Hidalgo             ";
states = "Tlaxcala            ";  states = "Yucatán             "; states = "Querétaro           ";
states = "Veracruz            ";  states = "San Luis Potosí     "; states = "Durango             ";
states = "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  + " " + capitals  + " " + areasSqrKms  + "  " + areasSqrMiles  + "        " + ordersOfAdmissionToFederation);
WriteLine("2  " + states  + " " + capitals  + " " + areasSqrKms  + "  " + areasSqrMiles  + "        " + ordersOfAdmissionToFederation);
WriteLine("3  " + states  + " " + capitals  + " " + areasSqrKms  + "  " + areasSqrMiles  + "        " + ordersOfAdmissionToFederation);
WriteLine("4  " + states  + " " + capitals  + " " + areasSqrKms  + "  " + areasSqrMiles  + "        " + ordersOfAdmissionToFederation);
WriteLine("5  " + states  + " " + capitals  + " " + areasSqrKms  + "  " + areasSqrMiles  + "        " + ordersOfAdmissionToFederation);
WriteLine("6  " + states  + " " + capitals  + " " + areasSqrKms  + "  " + areasSqrMiles  + "        " + ordersOfAdmissionToFederation);
WriteLine("7  " + states  + " " + capitals  + " " + areasSqrKms  + "  " + areasSqrMiles  + "        " + ordersOfAdmissionToFederation);
WriteLine("8  " + states  + " " + capitals  + " " + areasSqrKms  + "  " + areasSqrMiles  + "        " + ordersOfAdmissionToFederation);
WriteLine("9  " + states  + " " + capitals  + " " + areasSqrKms  + "  " + areasSqrMiles  + "        " + ordersOfAdmissionToFederation);
WriteLine("10 " + states  + " " + capitals  + " " + areasSqrKms  + "  " + areasSqrMiles  + "        " + ordersOfAdmissionToFederation);
WriteLine("11 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("12 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("13 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("14 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("15 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("16 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("17 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("18 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("19 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("20 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("21 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("22 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("23 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("24 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("25 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("26 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("27 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("28 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("29 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("30 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("31 " + states + " " + capitals + " " + areasSqrKms + "  " + areasSqrMiles + "        " + ordersOfAdmissionToFederation);
WriteLine("===============================================================================");```
2. To execute the application, on the main menu, click Debug -> Start Without Debugging
```===============================================================================

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

• If each value is a number without a decimal part, the compiler checks their range and concludes whether the array needs 32 bits or 64 bits. Here is an example:
```var naturals = new[] { 2735, 20, 3647597, 3408, 957 };
dynamic values = new[] { 0x91FF22, 8168, 0x80080, 0xF822FF, 202684 };```
• If the values are numeric but at least one of them includes a decimal part, the compiler concludes that the array is made of floating-point numbers. If you want to control their precision (float, double, or decimal), add the appropriate suffix to each value. This also means that you can use a combination of natural and decimal numbers, but the presence of at least one number with a decimal part would convert the array into floating point instead of int-based. Here is an example:
```var singles = new[] { 1244F, 525.38F, 6.28F, 2448.32F, 632.04F };
var doubles = new[] { 3.212D, 3047.098D, 732074.02, 18342.3579 };
var values = new[] { 17.230M, 4808237M, 222.4203M, 948.002009M };```
• If the values of the members are included in double-quotes, then the array will be considered a group of strings. Here is an example:
`var friends = new[] { "Mark", "Frank", "Charlotte", "Jerry" };`

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);
Console.Write("Number: ");
Console.WriteLine(doubles);
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;

numbers = 12.44;
numbers = 525.38;
numbers[GetIndex()] = 6.28;
numbers = 2448.32;
numbers = 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;

numbers = 12.44;
numbers = 525.38;
numbers[GetIndex()] = 6.28;
numbers = 2448.32;
numbers = 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;

numbers = 12.44;
numbers = 525.38;
numbers[GetIndex()] = 6.28;
numbers[SpecifyIndex()] = SpecifyValue();
numbers = 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;

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;

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;

system = Initialize();

Console.WriteLine(\$"Number: {system}");
Console.WriteLine(\$"Number: {system}");
Console.WriteLine(\$"Number: {system}");
Console.WriteLine(\$"Number: {system}");
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 + ", " + pts + "), Q(" + pts + ", " + pts + ")");
}```

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 + ", " + pts + "), Q(" + pts + ", " + pts + ")");
}```

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;

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;

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 + ", " + pts + "), Q(" + pts + ", " + pts + ")");
}```

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;

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 + ", " + pts + "), Q(" + pts + ", " + pts + ")");
}```

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

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

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

`string[] degrees = new string { "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;

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}");
Console.WriteLine(\$"House Style: {housePlans}");
Console.WriteLine(\$"House Style: {housePlans}");
Console.WriteLine(\$"House Style: {housePlans}");
Console.WriteLine(\$"House Style: {housePlans}");
Console.WriteLine(\$"House Style: {housePlans}");
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 Learning: Ending the Lesson

• Close your programming environment
 Previous Copyright © 2001-2022, FunctionX Monday 11 October 2021 Next