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:

@{
    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 main menu, click File -> New -> Project...
  3. In the middle list, click ASP.NET Web Application (.NET Framework) and change the Name of the project to CountriesStatistics02
  4. Click OK
  5. In the templates list of the New ASP.NET Web Application dialog box, click the MVC icon and click OK
  6. In the Solution Explorer, right-click Content -> Add -> Style Sheet
  7. Type CountriesStatistics as the name of the file
  8. Click OK
  9. Create the following styles in the document:
    body {
    }
    
    .navbar-inverse {
        background-color: #8d3434;
        border-bottom: 5px solid black; }
    
    .col-md-3 {
        min-height: 350px;
        background-color: #af8673; }
    
    .col-md-4 { width: 30%; }
    
    .row { margin-right: 0;
           margin-left:  0; }
    
    .jumbotron { margin-bottom:    3px;
                 background-color: antiquewhite; }
    
    .left-menu-group { list-style-type: none; }
    
    .left-menu-title {
        font-weight: 600;
        margin-left: -10px;
        padding-left: 20px;
        width: 280px;
        font-size: 1.55em;
        height: 1.62em;
        color: lightyellow;
        border-bottom: 2px solid black;
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; }
    
    .left-menu-group li {
        margin-left: -45px;
        padding-left: 20px;
        height: 1.62em;
        font-size: 1.35em;
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; }
    
    .left-menu-group li:hover {
        font-size: 1.35em;
        background-color: antiquewhite;
        border: 1px dashed maroon;  }
    
    .centralizer {
        margin: auto;
        width: 710px; }
    
    .tblStates {
        margin: auto;
        width: 320px; }
    
    .tblStates table { width: 100%; }
  10. In the Solution Explorer, expand Controllers and double-click HomeController.cs to open it
  11. Change the document as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace CountriesStatistics02.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
    
            public ActionResult Mexico()
            {
                return View();
            }
        }
    }
  12. In the Solution Explorer, expand Views and right-click Home -> Add -> New Scaffolded Item...
  13. In the Add Scaffold dialog box, in the middle frame, click MVC 5 View
  14. Click Add
  15. Type Mexico as the name of the view
  16. Click Add
  17. Change the document as follows:
    @{
        ViewBag.Title = "United Mexican States";
    }
    
    <h2>United Mexican States</h2>
    
    @{
    
    }
  18. In the Solution Explorer, under Views and under Home, double-click Index.cshtml
  19. Change the document as follows:
    @{
        ViewBag.Title = "Welcome";
        ViewBag.MainTitle = "Introduction";
    }
    
    <div class="jumbotron">
        <h1>Countries Statistics</h1>
        <p class="lead">This is a collection of resources that will assist you in studying some of the
            resources that various countries of this world offer, for both academic and entertainment purposes.</p>
    </div>
    
    <div class="row">
        <div class="col-md-3">
            <p class="left-menu-title">Topics</p>
            <ul class="left-menu-group">
                <li>History</li>
                <li>Tourism</li>
                <li>Sports</li>
                <li>Things to Do</li>
            </ul>
        </div>
        <div class="row">
            <div class="col-md-4">
                <h3>Australia</h3>
                <p>This section reviews the states and territories of Australia, including much information
                    about the government and the economy.</p>
                <p><a class="btn btn-warning" href="https://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p>
            </div>
            <div class="col-md-4">
                <h3>Germany</h3>
                <p>The history, sport, geography, and politics of Germany are described in this section
                    of our website.</p>
                <p><a class="btn btn-warning" href="https://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p>
            </div>
            <div class="col-md-4">
                <h3>Mexico</h3>
                <p>The various states of Mexico are described here. The tourism, culture, and entertaining
                    aspects of the country are also presented.</p>
                @Html.ActionLink("Mexico", "Mexico", "Home", null, new { @class = "btn btn-warning" })
            </div>
            <div class="col-md-4">
                <h3>United States</h3>
                <p>This library of documents can help get acquainted with the states of the USA, their
                    local histories and the touristic parks they have.</p>
                <p><a class="btn btn-warning" href="https://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p>
            </div>
        </div>
    </div>
  20. In the Solution Explorer, under Views, expand Shared and double-click _Layout.cshtml
  21. Change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.MainTitle :: @ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    <link rel="stylesheet" type="text/css" href="~/Content/CountriesStatistics.css" />
    </head>
    <body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="centralizer">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    @Html.ActionLink("Countries Statistics", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
    
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Continents", "Index", "Home")</li>
                        <li>@Html.ActionLink("Flags", "About", "Home")</li>
                        <li>@Html.ActionLink("Maps", "Index", "Home")</li>
                        <li>@Html.ActionLink("About Us", "About", "Home")</li>
                        <li>@Html.ActionLink("Contact Us", "Contact", "Home")</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <h4 class="text-center">&copy; @DateTime.Now.Year -- Countries Statistics --</h4>
        </footer>
    </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
  22. Access the Index.cshtml file of the Home view and, to execute the project, on the main menu, click Debug -> Start Without Debugging

    A Simple Form

  23. Close the middle browser and return to your programming environment
  24. In the Solution Explorer, under Views and under Home, double-click Mexico.cshtml

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

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

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

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

@{
    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 a Group

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:

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

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

<p>Number: @numbers[3]</p>

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

Practical LearningPractical Learning: Accessing the Items of an Array

  1. Change the code as follows:
    @{
        ViewBag.Title = "United Mexican States";
    }
    
    <h2>United Mexican States</h2>
    
    @{
        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 };
    }
    
    <table border="6" style="width: 660px" cellpadding="2" cellspacing="1">
        <tr>
            <td class="text-center">&nbsp;</td>
            <td>&nbsp;</td>
            <td colspan="2" class="text-center"><b>Area</b></td>
            <td class="text-center"><b>Admission to Federation</b></td>
            <td>&nbsp;</td>
        </tr>
        <tr>
            <td class="text-center short-text">#</td>
            <td><b>State Name</b></td>
            <td class="text-center"><b>Sqr Kms</b></td>
            <td class="text-center"><b>Sqr Miles</b></td>
            <td class="text-center"><b>Order</b></td>
            <td><b>Capital</b></td>
        </tr>
        <tr>
            <td class="text-center">1</td><td>@states[0]</td><td class="text-right">@areasSqrKms[0]</td><td class="text-right">@areasSqrMiles[0]</td><td class="text-center">@ordersOfAdmissionToFederation[0]</td><td>@capitals[0]</td>
        </tr>
        <tr>
            <td class="text-center">2</td><td>@states[1]</td><td class="text-right">@areasSqrKms[1]</td><td class="text-right">@areasSqrMiles[1]</td><td class="text-center">@ordersOfAdmissionToFederation[1]</td><td>@capitals[1]</td>
        </tr>
        <tr>
            <td class="text-center">3</td><td>@states[2]</td><td class="text-right">@areasSqrKms[2]</td><td class="text-right">@areasSqrMiles[2]</td><td class="text-center">@ordersOfAdmissionToFederation[2]</td><td>@capitals[2]</td>
        </tr>
        <tr>
            <td class="text-center">4</td><td>@states[3]</td><td class="text-right">@areasSqrKms[3]</td><td class="text-right">@areasSqrMiles[3]</td><td class="text-center">@ordersOfAdmissionToFederation[3]</td><td>@capitals[3]</td>
        </tr>
        <tr>
            <td class="text-center">5</td><td>@states[4]</td><td class="text-right">@areasSqrKms[4]</td><td class="text-right">@areasSqrMiles[4]</td><td class="text-center">@ordersOfAdmissionToFederation[4]</td><td>@capitals[4]</td>
        </tr>
        <tr>
            <td class="text-center">6</td><td>@states[5]</td><td class="text-right">@areasSqrKms[5]</td><td class="text-right">@areasSqrMiles[5]</td><td class="text-center">@ordersOfAdmissionToFederation[5]</td><td>@capitals[5]</td>
        </tr>
        <tr>
            <td class="text-center">7</td><td>@states[6]</td><td class="text-right">@areasSqrKms[6]</td><td class="text-right">@areasSqrMiles[6]</td><td class="text-center">@ordersOfAdmissionToFederation[6]</td><td>@capitals[6]</td>
        </tr>
        <tr>
            <td class="text-center">8</td><td>@states[7]</td><td class="text-right">@areasSqrKms[7]</td><td class="text-right">@areasSqrMiles[7]</td><td class="text-center">@ordersOfAdmissionToFederation[7]</td><td>@capitals[7]</td>
        </tr>
        <tr>
            <td class="text-center">9</td><td>@states[8]</td><td class="text-right">@areasSqrKms[8]</td><td class="text-right">@areasSqrMiles[8]</td><td class="text-center">@ordersOfAdmissionToFederation[8]</td><td>@capitals[8]</td>
        </tr>
        <tr>
            <td class="text-center">10</td><td>@states[9]</td><td class="text-right">@areasSqrKms[9]</td><td class="text-right">@areasSqrMiles[9]</td><td class="text-center">@ordersOfAdmissionToFederation[9]</td><td>@capitals[9]</td>
        </tr>
        <tr>
            <td class="text-center">11</td><td>@states[10]</td><td class="text-right">@areasSqrKms[10]</td><td class="text-right">@areasSqrMiles[10]</td><td class="text-center">@ordersOfAdmissionToFederation[10]</td><td>@capitals[10]</td>
        </tr>
        <tr>
            <td class="text-center">12</td><td>@states[11]</td><td class="text-right">@areasSqrKms[11]</td><td class="text-right">@areasSqrMiles[11]</td><td class="text-center">@ordersOfAdmissionToFederation[11]</td><td>@capitals[11]</td>
        </tr>
        <tr>
            <td class="text-center">13</td><td>@states[12]</td><td class="text-right">@areasSqrKms[12]</td><td class="text-right">@areasSqrMiles[12]</td><td class="text-center">@ordersOfAdmissionToFederation[12]</td><td>@capitals[12]</td>
        </tr>
        <tr>
            <td class="text-center">14</td><td>@states[13]</td><td class="text-right">@areasSqrKms[13]</td><td class="text-right">@areasSqrMiles[13]</td><td class="text-center">@ordersOfAdmissionToFederation[13]</td><td>@capitals[13]</td>
        </tr>
        <tr>
            <td class="text-center">15</td><td>@states[14]</td><td class="text-right">@areasSqrKms[14]</td><td class="text-right">@areasSqrMiles[14]</td><td class="text-center">@ordersOfAdmissionToFederation[14]</td><td>@capitals[14]</td>
        </tr>
        <tr>
            <td class="text-center">16</td><td>@states[15]</td><td class="text-right">@areasSqrKms[15]</td><td class="text-right">@areasSqrMiles[15]</td><td class="text-center">@ordersOfAdmissionToFederation[15]</td><td>@capitals[15]</td>
        </tr>
        <tr>
            <td class="text-center">17</td><td>@states[16]</td><td class="text-right">@areasSqrKms[16]</td><td class="text-right">@areasSqrMiles[16]</td><td class="text-center">@ordersOfAdmissionToFederation[16]</td><td>@capitals[16]</td>
        </tr>
        <tr>
            <td class="text-center">18</td><td>@states[17]</td><td class="text-right">@areasSqrKms[17]</td><td class="text-right">@areasSqrMiles[17]</td><td class="text-center">@ordersOfAdmissionToFederation[17]</td><td>@capitals[17]</td>
        </tr>
        <tr>
            <td class="text-center">19</td><td>@states[18]</td><td class="text-right">@areasSqrKms[18]</td><td class="text-right">@areasSqrMiles[18]</td><td class="text-center">@ordersOfAdmissionToFederation[18]</td><td>@capitals[18]</td>
        </tr>
        <tr>
            <td class="text-center">20</td><td>@states[19]</td><td class="text-right">@areasSqrKms[19]</td><td class="text-right">@areasSqrMiles[19]</td><td class="text-center">@ordersOfAdmissionToFederation[19]</td><td>@capitals[19]</td>
        </tr>
        <tr>
            <td class="text-center">21</td><td>@states[20]</td><td class="text-right">@areasSqrKms[20]</td><td class="text-right">@areasSqrMiles[20]</td><td class="text-center">@ordersOfAdmissionToFederation[20]</td><td>@capitals[20]</td>
        </tr>
        <tr>
            <td class="text-center">22</td><td>@states[21]</td><td class="text-right">@areasSqrKms[21]</td><td class="text-right">@areasSqrMiles[21]</td><td class="text-center">@ordersOfAdmissionToFederation[21]</td><td>@capitals[21]</td>
        </tr>
        <tr>
            <td class="text-center">23</td><td>@states[22]</td><td class="text-right">@areasSqrKms[22]</td><td class="text-right">@areasSqrMiles[22]</td><td class="text-center">@ordersOfAdmissionToFederation[22]</td><td>@capitals[22]</td>
        </tr>
        <tr>
            <td class="text-center">24</td><td>@states[23]</td><td class="text-right">@areasSqrKms[23]</td><td class="text-right">@areasSqrMiles[23]</td><td class="text-center">@ordersOfAdmissionToFederation[23]</td><td>@capitals[23]</td>
        </tr>
        <tr>
            <td class="text-center">25</td><td>@states[24]</td><td class="text-right">@areasSqrKms[24]</td><td class="text-right">@areasSqrMiles[24]</td><td class="text-center">@ordersOfAdmissionToFederation[24]</td><td>@capitals[24]</td>
        </tr>
        <tr>
            <td class="text-center">26</td><td>@states[25]</td><td class="text-right">@areasSqrKms[25]</td><td class="text-right">@areasSqrMiles[25]</td><td class="text-center">@ordersOfAdmissionToFederation[25]</td><td>@capitals[25]</td>
        </tr>
        <tr>
            <td class="text-center">27</td><td>@states[26]</td><td class="text-right">@areasSqrKms[26]</td><td class="text-right">@areasSqrMiles[26]</td><td class="text-center">@ordersOfAdmissionToFederation[26]</td><td>@capitals[26]</td>
        </tr>
        <tr>
            <td class="text-center">28</td><td>@states[27]</td><td class="text-right">@areasSqrKms[27]</td><td class="text-right">@areasSqrMiles[27]</td><td class="text-center">@ordersOfAdmissionToFederation[27]</td><td>@capitals[27]</td>
        </tr>
        <tr>
            <td class="text-center">29</td><td>@states[28]</td><td class="text-right">@areasSqrKms[28]</td><td class="text-right">@areasSqrMiles[28]</td><td class="text-center">@ordersOfAdmissionToFederation[28]</td><td>@capitals[28]</td>
        </tr>
        <tr>
            <td class="text-center">30</td><td>@states[29]</td><td class="text-right">@areasSqrKms[29]</td><td class="text-right">@areasSqrMiles[29]</td><td class="text-center">@ordersOfAdmissionToFederation[29]</td><td>@capitals[29]</td>
        </tr>
        <tr>
            <td class="text-center">31</td><td>@states[30]</td><td class="text-right">@areasSqrKms[30]</td><td class="text-right">@areasSqrMiles[30]</td><td class="text-center">@ordersOfAdmissionToFederation[30]</td><td>@capitals[30]</td>
        </tr>
    </table>
    
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging

    Accessing the Members of an Array

  3. Close the browser 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 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 };
    dynamic doubles = new[] { 3.212D, 3047.098D, 732074.02, 18342.3579 };
}

<p>Number: @singles[2]</p>
<p>Number: @doubles[0]</p>

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 method. Here is an example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Exercise.Controllers
{
    public class HomeController : Controller
    {
        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:

@{
    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. In this case, the value of each member must be, or must be evaluated to, true or false. Here is an example:

@{
    bool[] fullTimeStudents = new bool[] { true, true, true, false, true, false };
}

As stated already, 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:

@{
    double house1Value = 460885.85D;
    double house2Value = 685770.00D;

    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:

using System.Web.Mvc;

namespace Exercise.Controllers
{
    public class HomeController : Controller
    {
        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:

using System.Web.Mvc;

namespace Exercise.Controllers
{
    public class HomeController : Controller
    {
        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:

<!DOCTYPE html>
<html>
<head>
<title>Coordinate System</title>
</head>
<body>
@{
    CoordinateSystem cs = new CoordinateSystem();

    <p>Points Coordinates:</p>
    <p>P(@cs.Points[0], @cs.Points[1])</p>
    <p>Q(@cs.Points[2], @cs.Points[3])</p>
}

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 returns another array as argument.

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:

<!DOCTYPE html>
<html>
<head>
<title>Coordinate System</title>
</head>
<body>
@{
    int[] system = new int[4];
    CoordinateSystem coordinates = new CoordinateSystem();

    system = coordinates.Initialize();
}

The method could also be called as follows:

<!DOCTYPE html>
<html>
<head>
<title>Coordinate System</title>
</head>
<body>
@{
    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:

<!DOCTYPE html>
<html>
<head>
<title>Coordinate System</title>
</head>
<body>
@{
    CoordinateSystem coordinates = new CoordinateSystem();

    var coord = coordinates.Initialize();
    dynamic point = coordinates.Initialize();
}
</body>
</html>

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 CoordinateSystemController : Controller
{
    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:

<!DOCTYPE html>
<html>
<head>
<title>Coordinate System</title>
</head>
<body>
@{
    CoordinateSystem coordinates = new CoordinateSystem();

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

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[] { 12, 5, -2, -2 };

        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:

<!DOCTYPE html>
<html>
<head>
<title>Coordinate System</title>
</head>
<body>
@{
    CoordinateSystem coordinates = new CoordinateSystem();

    int[] points = new int[4];

    coordinates.CreateCoordinate(points);
}
    
<p>Points Coordinates</p>

<p>@coordinates.Message</p>
</body>
</html>

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[] { 12, 5, -2, -2 };

        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:

<!DOCTYPE html>
<html>
<head>
<title>Coordinate System</title>
</head>
<body>
@{
    CoordinateSystem coordinates = new CoordinateSystem();

    int[] points = new int[4];

    coordinates.CreateCoordinate(ref points);
}

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:

public class CoordinateSystem
{
    public string Message;

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

        Message = "P(" + pts[0] + ", " + pts[1] + "), Q(" + pts[2] + ", " + pts[1] + ")";
    }
}
----------------------------------------------
<!DOCTYPE html>
<html>
<head>
<title>Coordinate System</title>
</head>
<body>
@{
    CoordinateSystem coordinates = new CoordinateSystem();

    int[] points = new int[4];

    coordinates.CreateCoordinate(out points);
}
    
<p>Points Coordinates</p>

<p>@coordinates.Message</p>
</body>
</html>

Passing a Varied Number of Parameters

When you oass 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:

<!DOCTYPE html>
<html>
<head>
<title>Coordinate System</title>
</head>
<body>
@{
    int[] system = new int[4];
    CoordinateSystem coordinates = new CoordinateSystem();
}

@{
    // The method is called with one argument
    coordinates.Describe(-6);
}
<p>@coordinates.Message</p>
@{
    // The method is called with 4 arguments
    coordinates.Describe(2, 2, 5, -3);
}
<p>@coordinates.Message</p>
@{
    // The method is called with two arguments
    coordinates.Describe(2, 5);
}
<p>@coordinates.Message</p>
@{
    // The method is called with three arguments
    coordinates.Describe(-4, 3, 1);
}
<p>@coordinates.Message</p>
</body>
</html>

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2008-2019, FunctionX Next