An Array of Objects

Introduction

You can create an array of values where each member of the array is based on a formal class. Of course, you must have a class first. You can use one of the already available classes of the .NET Framework or you can create your own class. Here is an example of such a class:

public enum EmploymentStatus
{
    FullTime,
    PartTime,
    Unknown
}

public class Employee
{
    public long EmployeeNumber     { get; set; }
    public string EmployeeName     { get; set; }
    public EmploymentStatus Status { get; set; }
    public double HourlySalary     { get; set; }
}

Practical LearningPractical Learning: Introducing Arrays and Classes

  1. Save the following picture to your computer

    Globe

  2. Start Microsoft Visual Studio
  3. On the main menu, click File -> New -> Project...
  4. In the middle list, click ASP.NET Web Application (.NET Framework) and change the Name of the project to CountriesStatistics05
  5. Click OK
  6. In the templates list of the New ASP.NET Web Application dialog box, click the MVC icon and click OK
  7. In the Solution Explorer, right-click Models -> Add -> New Item...
  8. In the left frame of the Add New Item dialog box, click Code and, in the middle frame, click Interface
  9. Change the Name to Abbreviated
  10. Click Add
  11. Create a string-based property as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace CountriesStatistics05.Models
    {
        interface IAbbreviated
        {
            string Abbreviation { get; set; }
        }
    }
    
  12. In the Solution Explorer, right-click Models -> Add -> Class...
  13. Type GovernmentEntity as the name of the file
  14. Click Add
  15. Change the class as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace CountriesStatistics05.Models
    {
        public abstract class GovernmentEntity
        {
            public virtual string StateName  { get; set; }
            public virtual int AreaSqrKms { get; set; }
            public virtual string Capital    { get; set; }
        }
    }
  16. In the Solution Explorer, right-click App_Code -> Add -> Class...
  17. Type State as the name of the file
  18. Press Enter
  19. Change the class as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace CountriesStatistics05.Models
    {
        public class State : GovernmentEntity,
                             IAbbreviated
        {
            public string Abbreviation { get; set; }
        }
    }
  20. In the Solution Explorer, right-click CountriesStatistics05 -> Add -> New Folder
  21. Type Images and press Enter
  22. Add the above picture to the Images folder
  23. In the Solution Explorer, right-click Content -> Add -> Style Sheet
  24. Type CountriesStatistics as the name of the file
  25. Click OK
  26. 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%;  }
    .col-md-9 { padding-left: 80px; }
    
    .row {
        margin-right: 0;
        margin-left:  0; }
    
    .jumbotron {
        margin-bottom:    3px;
        background-color: #FFCC80; }
    
    .left-menu-group { list-style-type: none; }
    
    .left-menu-title {
        font-weight:   600;
        margin-left:  -10px;
        padding-left:  20px;
        width:         100%;
        font-size:     1.55em;
        height:        1.62em;
        color:         lightyellow;
        border-bottom: 2px solid yellow;
        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:  800px; }
    
    .tblStates {
        margin: auto;
        width:  320px; }
    
    .tblStates table { width: 100%; }
  27. In the Solution Explorer, right-click Controllers -> Add -> New Scaffolded Item...
  28. In the middle frame of the Add Scaffold dialog box, click MVC 5 Controller - Empty
  29. Click Add
  30. Type Australia to get AustraliaController
  31. Click Add
  32. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  33. In the middle frame of the Add Scaffold dialog box, make sure MVC 5 Controller - Empty is selected and click Add
  34. Type Germany to get GermanyController
  35. Press Enter
  36. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  37. In the middle frame of the Add Scaffold dialog box, make sure MVC 5 Controller - Empty is selected and click Add
  38. Type Mexico to get MexicoController
  39. Click Add
  40. In the Solution Explorer, right-click Controllers -> Add -> New Scaffolded Item...
  41. In the middle frame of the Add Scaffold dialog box, make sure MVC 5 Controller - Empty is selected and click Add
  42. Type UnitedStates to get UnitedStatesController
  43. Click Add
  44. In the Solution Explorer, under Views, right-click Australia -> Add -> View...
  45. Type Index as the name of the view
  46. Click Add
  47. In the Solution Explorer, under Views, right-click Germany -> Add -> View...
  48. Type Index as the name of the view
  49. Click Add
  50. In the Solution Explorer, under Views, right-click Mexico -> Add -> View...
  51. Type Index as the name of the view
  52. Click Add
  53. In the Solution Explorer, under Views, right-click UnitedStates -> Add -> View...
  54. Type Index as the name of the view
  55. Click Add
  56. In the Solution Explorer, under Views, expand Home and double-click Index (under Home)
  57. Change the document as follows:
    @{
        ViewBag.Title = "Welcome";
        ViewBag.MainTitle = "Countries Statistics";
    }
    
    <div class="jumbotron">
        <div class="row">
            <div class="col-md-2">
                <img src="~/Images/globe1.png" alt="Globe" width="220" height="220" />
            </div>
            <div class="col-md-9">
                <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>
    </div>
    
    <div class="row">
        <div class="col-md-3">
            <p class="left-menu-title">Topics</p>
            <ul class="left-menu-group">
                <li>Sports</li>
                <li>History</li>
                <li>Tourism</li>
                <li>Careers</li>
                <li>Research</li>
                <li>Organizations</li>
                <li>Education/Training</li>
                <li>Academic Resources</li>
            </ul>
        </div>
        <div class="row">
            <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
                    different histories and the touristic parks they have.</p>
                @Html.ActionLink("United States", "Index", "UnitedStates", null, new { @class = "btn btn-warning" })
            </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>
                @Html.ActionLink("Germany", "Index", "Germany", null, new { @class = "btn btn-warning" })
            </div>
            <div class="col-md-4">
                <h3>Australia</h3>
                <p>This section reviews the states and territories of Australia, including much information
                    about the government the country's economy.</p>
                @Html.ActionLink("Australia", "Index", "Australia", null, new { @class = "btn btn-warning" })
            </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", "Index", "Mexico", null, new { @class = "btn btn-warning" })
            </div>
        </div>
    </div>
  58. In the Solution Explorer, under Views, expand Shared and double-click _Layout.cshtml
  59. 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", "UnitedStates", null, null)</li>
                            <li>@Html.ActionLink("Flags", "Index", "Germany", null, null)</li>
                            <li>@Html.ActionLink("Maps", "Index", "Australia", null, null)</li>
                            <li>@Html.ActionLink("Resources", "Index", "Mexico", null, null)</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>
  60. To execute the project, on the main menu, click Debug -> Start Without Debugging

    A Simple Form

  61. Close the middle browser and return to your programming environment
  62. In the Solution Explorer, under Views and under Australia, double-click Index.cshtml
  63. Change the document as follows:
    @{
        ViewBag.Title = "Commonwealth of Australia";
    }
    
    <h2 class="text-center">Commonwealth of Australia</h2>
    
    @{
    
    }

Creating an Array of Objects

To create a list of objects, you can declare an array variable and use the square brackets to specify its size. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Employees Records</title>
</head>
<body>
<div>
<h1>Employees Records</h1>

@{
    Employee[] staffMembers = new Employee[3];
}
</div>
</body>
</html>

You can also use the var or the dynamic keyword to create the array but omit the first square brackets. Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Employees Records</title>
</head>
<body>
<div>
<h1>Employees Records</h1>

@{
    var staffMembers = new Employee[8];
    dynamic contractors = new Employee[5];
}
</div>
</body>
</html>

ApplicationPractical Learning: Creating an Array of Objects

Initializing an Array of Objects

If you create an array of objects, you can then access each member using its index, allocate memory for it using the new operator, then access each of its fields or properties, still using its index, to assign it the desired value. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Employees Records</title>
</head>
<body>
<div>
<h1>Employees Records</h1>

@{
    Employee[] staffMembers = new Employee[3];

    staffMembers[0] = new Employee();
    staffMembers[0].EmployeeNumber = 20204;
    staffMembers[0].EmployeeName = "Harry Fields";
    staffMembers[0].Status = EmploymentStatus.FullTime;
    staffMembers[0].HourlySalary = 16.85;

    staffMembers[1] = new Employee();
    staffMembers[1].EmployeeNumber = 92857;
    staffMembers[1].EmployeeName = "Jennifer Almonds";
    staffMembers[1].Status = EmploymentStatus.FullTime;
    staffMembers[1].HourlySalary = 22.25;

    staffMembers[2] = new Employee();
    staffMembers[2].EmployeeNumber = 42963;
    staffMembers[2].EmployeeName = "Sharon Culbritt";
    staffMembers[2].Status = EmploymentStatus.PartTime;
    staffMembers[2].HourlySalary = 10.95;
}
</div>
</body>
</html>

As an alternative, you can initialize each member of the array when creating it. To do this, you may need a constructor that takes each member you want to initialize, as argument. Here is an example of such a constructor:

public enum EmploymentStatus
{
    FullTime,
    PartTime,
    Unknown
};

public class Employee
{
    public long EmployeeNumber     { get; set; }
    public string EmployeeName     { get; set; }
    public EmploymentStatus Status { get; set; }
    public double HourlySalary     { get; set; }

    public Employee(long number, string name,
                    EmploymentStatus emplStatus, double salary)
    {
        EmployeeNumber = number;
        EmployeeName = name;
        Status = emplStatus;
        HourlySalary = salary;
    }
}

To initialize an object, before the semi-colon of creating the array, open the curly brackets, allocate memory for each member and specify the value of each field or property. Here are examples:

@{
    Employee[] staffMembers = new Employee[]
    {
        new Employee(20204, "Harry Fields", EmploymentStatus.FullTime, 16.85),
        new Employee(92857, "Jennifer Almonds", EmploymentStatus.FullTime, 22.25),
        new Employee(42963, "Sharon Culbritt", EmploymentStatus.PartTime, 10.95)
    };
}

If using the var or the dynamic keyword and a constructor to initialize the array, you can omit calling the name of the class before the square brackets. Here is an example:

@{
    var staffMembers = new[]
    {
        new Employee(20204, "Harry Fields", EmploymentStatus.FullTime, 16.85),
        new Employee(92857, "Jennifer Almonds", EmploymentStatus.FullTime, 22.25),
        new Employee(42963, "Sharon Culbritt", EmploymentStatus.PartTime, 10.95)
    };
}

ApplicationPractical Learning: Initializing an Array of Objects

Accessing the Members of an Array of Objects

Accessing an Object by Index

After creating and initializing the array, you can use it as you see fit. For example, you may want to display its values to the user. You can access any member of the array by its index, then use the same index to get its field(s) and consequently its (their) value(s). Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Employee Records</title>
</head>
<body>
    <h1>Employee Record</h1>

    @{
        Employee[] staffMembers = new Employee[]
        {
            new Employee(20204, "Harry Fields", EmploymentStatus.FullTime, 16.85),
            new Employee(92857, "Jennifer Almonds", EmploymentStatus.FullTime, 22.25),
            new Employee(42963, "Sharon Culbritt", EmploymentStatus.PartTime, 10.95)
        };
    }

    <table border="2">
        <tr>
            <td style="width: 120px"><b>Employee #:</b></td>
            <td style="width: 120px">@staffMembers[2].EmployeeNumber</td>
        </tr>
        <tr>
            <td><b>Full Name:</b></td>
            <td>@staffMembers[2].EmployeeName</td>
        </tr>
        <tr>
            <td><b>Status:</b</td>
            <td>@staffMembers[2].Status</td>
        </tr>
        <tr>
            <td><b>Hourly Salary:</b></td>
            <td>@staffMembers[2].HourlySalary</td>
        </tr>
    </table>
</body>
</html>

This would produce:

Accessing the Members of the Array

Once again, remember that the index you use must be between 0 (included) and the number of objects - 1. Otherwise, the webpage would throw an exception.

Looping to Access an Object

In the same way, you can use a loop (while, do...while, or for) to access all members of the array using their index.

Practical LearningPractical Learning: Looping for an Array of Objects

  1. To present the list of states, add the follow code:
    @{
        ViewBag.Title = "Commonwealth of Australia";
    }
    
    <h2 class="text-center">Commonwealth of Australia</h2>
    
    @{
        StatesStatistics62.App_Code.State[] states = new StatesStatistics62.App_Code.State[6];
    
        states[0] = new StatesStatistics62.App_Code.State() { Abbreviation = "WA", StateName = "Western Australia", AreaSqrKms = 2529875, Capital = "Perth" };
        states[1] = new StatesStatistics62.App_Code.State() { Abbreviation = "SA", StateName = "South Australia", AreaSqrKms = 983482, Capital = "Adelaide" };
        states[2] = new StatesStatistics62.App_Code.State() { Abbreviation = "QLD", StateName = "Queensland", AreaSqrKms = 1730648, Capital = "Brisbane" };
        states[3] = new StatesStatistics62.App_Code.State() { Abbreviation = "NSW", StateName = "New South Wales", AreaSqrKms = 800642, Capital = "Sydney" };
        states[4] = new StatesStatistics62.App_Code.State() { Abbreviation = "VIC", StateName = "Victoria", AreaSqrKms = 227416, Capital = "Melbourne" };
        states[5] = new StatesStatistics62.App_Code.State() { Abbreviation = "TAS", StateName = "Tasmania", AreaSqrKms = 68401, Capital = "Hobart" };
    }
    
    <table border="6" style="width: 450px" cellpadding="2" cellspacing="1">
        <tr>
            <td class="text-center"><b>Abbreviation</b></td>
            <td class="text-center"><b>State Name</b></td>
            <td class="text-center"><b>Area</b></td>
            <td><b>Capital</b></td>
        </tr>
        @for (int counter = 0; counter < states.Length - 1; counter++)
        {
            <tr>
                <td class="text-center">@states[counter].Abbreviation</td>
                <td>@states[counter].StateName</td>
                <td class="text-right">@states[counter].AreaSqrKms Km<sup>2</sup></td>
                <td>@states[counter].Capital</td>
            </tr>
        }
    </table>
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    Introduction to Looping and Counting

  3. Close the browser and return to your programming environment

A Field as an Array

Introduction

Like a primitive type, an array of objects can be made a field of a class. You can primarily declare the array and specify its size. Here is an example:

public class CompanyRecords
{
    Employee[] employees = new Employee[12];
}

After doing this, you can then initialize the array from the index of each member. Alternatively, as we saw for field arrays of primitive types, you can declare the array in the body of the class, then use a constructor or another method of the class to allocate memory for it. Here is an example:

public class Employee
{

}

public class CompanyRecords
{
    Employee[] employees;

    public CompanyRecords()
    {
        employees = new Employee[12];
    }
}

Initializing a Field of Array Type

To initialize the array, remember that each member is a value that must be allocated on the heap. Therefore, apply the new operator on each member of the array to allocate its memory, and then initialize it. Here is an example:

public enum EmploymentStatus
{
    FullTime,
    PartTime,
    Unknown
};

public class Employee
{
    public long EmployeeNumber { get; set; }
    public string EmployeeName { get; set; }
    public EmploymentStatus Status { get; set; }
    public double HourlySalary { get; set; }
}

public class CompanyRecords
{
    Employee[] employees;

    public CompanyRecords()
    {
        employees = new Employee[2];

        employees[0] = new Employee();
        employees[0].EmployeeNumber = 70128;
        employees[0].EmployeeName = "Frank Dennison";
        employees[0].Status = EmploymentStatus.PartTime;
        employees[0].HourlySalary = 8.65;

        employees[1] = new Employee();
        employees[1].EmployeeNumber = 24835;
        employees[1].EmployeeName = "Jeffrey Arndt";
        employees[1].Status = EmploymentStatus.Unknown;
        employees[1].HourlySalary = 16.05;
    }
}

If the class used as field has an appropriate constructor, you can use it to initialize each member of the array. Here is an example:

public class CompanyRecords
{
    Employee[] employees;

    public CompanyRecords()
    {
	employees = new Employee[]
	{
            new Employee(70128, "Justine Hearson", EmploymentStatus.PartTime, 10.62),
            new Employee(24835, "Bertha Hack", EmploymentStatus.FullTime, 18.94),
            new Employee(70128, "Frank Dennison", EmploymentStatus.Seasonal, 12.48),
            new Employee(24835, "Jeffrey Arndt", EmploymentStatus.PartTime, 16.05),
	};
    }
}

Using the Array

Once you have created and initialized the array, you can use it as you see fit, such as displaying its values to the user. You must be able to access each member of the array, using its index. Once you have accessed a member of the array, you can get to its fields.

Properties of Array Types

The Value of a Property from an Array

You can create a property in a class so that the property is an array. If you want to use a property that includes both a getter and a setter sections, you can use a field that was created as an array. Here is an example:

public class Region
{
    public string Designation { get; set; }
    public string Description { get; set; }
}

public class State
{
    private Region[] rgn;

    public Region[] Area
    {
        get
        {
            return rgn;
        }
        set
        {
            rgn = value;
        }
    }
} 

Otherwise, you can create the property as an automatic one.

To specify the value of a property of array type, you can get an array member using its index and assign it to the desired member. Here are examples:

@{
    Region[] regions = new Region[]
    {
        new Region() { Designation = "East North Central" },
        new Region() { Designation = "East South Central" },
        new Region() { Designation = "New England"        }
    };

    State[] states = new State[15]
    {
        new State() { Region = regions[1], Abbreviation = "KY", StateName = "Kentucky" },
        new State() { StateName = "Maine", Region = regions[2], AreaSqrMiles =  35387 },
        new State() { Capital = "Boston", StateName = "Massachusetts", Region = regions[2] },
        new State() { Abbreviation = "AL", Region = regions[1], StateName = "Alabama" },
        new State() { Region = regions[0], StateName = "Michigan", AreaSqrMiles = 98810 }
    };
}

A Property of an Array Type

A property can be an array type. In this case, the values of the property would be held by an array.

Practical LearningPractical Learning: Creating a Property of Array Type

Initializing a Property of Array Type

To initialize a property that is an array or to specify its value(s), you can create an array and assign it to the property. You can also create the array directly on the property. If the main class is used as an array, all properties can have the same number of values or each property can have a different number of values.

Practical LearningPractical Learning: Initializing the Properties of Array Type

Accessing the Property

To get the value of each element of a property that is an array type, you can apply the square brackets to the property and pass the index of the desired element.

Practical LearningPractical Learning: Accessing a Property of an Array Type

  1. To use the array property, change the code as follows:
    @{
        ViewBag.Title = "Commonwealth of Australia";
    }
    
    <h2 class="text-center">Commonwealth of Australia</h2>
    
    @{
        string[] WesternAustralia = new string[3]
        {
            "Perth", "Ellenbrook", "Geraldton"
        };
        CountriesStatistics05.Models.State[] states = new CountriesStatistics05.Models.State[6];
    
        states[0] = new CountriesStatistics05.Models.State() { Abbreviation = "WA", StateName = "Western Australia", AreaSqrKms = 2529875, Capital = "Perth" };
        states[0].SignificanCities = WesternAustralia;
        states[1] = new CountriesStatistics05.Models.State() { Abbreviation = "SA", StateName = "South Australia", AreaSqrKms = 983482, Capital = "Adelaide" };
        states[1].SignificanCities = new string[]
        {
            "Adelaide", "Mount Gambier", "Port Lincoln"
        };
    
        states[2] = new CountriesStatistics05.Models.State()
        {
            Abbreviation = "QLD",
            StateName = "Queensland",
            AreaSqrKms = 1730648,
            Capital = "Brisbane",
            SignificanCities = new string[] { "Brisbane", "Sunshine Coast", "Gold Coast" }
        };
        states[3] = new CountriesStatistics05.Models.State()
        {
            Abbreviation = "NSW",
            StateName = "New South Wales",
            AreaSqrKms = 800642,
            Capital = "Sydney",
            SignificanCities = new string[] { "Sydney", "Newcastle", "Queanbeyan" }
        };
        states[4] = new CountriesStatistics05.Models.State() { Abbreviation = "VIC", StateName = "Victoria", AreaSqrKms = 227416, Capital = "Melbourne" };
        states[5] = new CountriesStatistics05.Models.State() { Abbreviation = "TAS", StateName = "Tasmania", AreaSqrKms = 68401, Capital = "Hobart" };
    
        states[4].SignificanCities = new string[] { "Geelong", "Ballarat", "Bendigo" };
        states[5].SignificanCities = new string[4];
        states[5].SignificanCities[0] = "Devonport";
        states[5].SignificanCities[1] = "Hobart";
        states[5].SignificanCities[2] = "Strahan";
    }
    
    <table border="6" style="width: 660px" cellpadding="2" cellspacing="1">
        <tr>
            <td class="text-center"><b>Abbreviation</b></td>
            <td class="text-center"><b>State Name</b></td>
            <td class="text-center"><b>Area</b></td>
            <td><b>Capital</b></td>
            <td><b>Significant Cities</b></td>
        </tr>
        @for (int counter = 0; counter < states.Length - 1; counter++)
        {
            <tr>
                <td class="text-center">@states[counter].Abbreviation</td>
                <td>@states[counter].StateName</td>
                <td class="text-right">@states[counter].AreaSqrKms Km<sup>2</sup></td>
                <td>@states[counter].Capital</td>
                <td>@states[counter].SignificanCities[0], @states[counter].SignificanCities[1], @states[counter].SignificanCities[2]</td>
            </tr>
        }
    </table>
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    Accessing a Property of an Array Type

  3. Return to your programming environment
  4. In the above code, each property had the same number of elements in the array. Fortunately, each property can have a different number of elements. For examples, change the code as follows:
    @{
        ViewBag.Title = "Commonwealth of Australia";
    }
    
    <h2 class="text-center">Commonwealth of Australia</h2>
    
    @{
        string[] WesternAustralia = new string[1] { "Perth" };
        CountriesStatistics05.Models.State[] states = new CountriesStatistics05.Models.State[6];
    
        states[0] = new CountriesStatistics05.Models.State() { Abbreviation = "WA", StateName = "Western Australia", AreaSqrKms = 2529875, Capital = "Perth" };
        states[0].SignificanCities = WesternAustralia;
        states[1] = new CountriesStatistics05.Models.State() { Abbreviation = "SA", StateName = "South Australia", AreaSqrKms = 983482, Capital = "Adelaide" };
        states[1].SignificanCities = new string[] { "Adelaide" };
    
        states[2] = new CountriesStatistics05.Models.State()
        {
            Abbreviation = "QLD", StateName = "Queensland", AreaSqrKms = 1730648, Capital = "Brisbane",
            SignificanCities = new string[] { "Brisbane", "Sunshine Coast", "Gold Coast", "Townsville", "Cairns", "Toowoomba" }
        };
        states[3] = new CountriesStatistics05.Models.State()
        {
            Abbreviation = "NSW", StateName = "New South Wales", AreaSqrKms = 800642, Capital = "Sydney",
            SignificanCities = new string[] { "Sydney", "Newcastle", "Queanbeyan", "Tweed Heads", "Maitland", "Wollongong", "Albury" }
        };
        states[4] = new CountriesStatistics05.Models.State() { Abbreviation = "VIC", StateName = "Victoria", AreaSqrKms = 227416, Capital = "Melbourne" };
        states[5] = new CountriesStatistics05.Models.State() { Abbreviation = "TAS", StateName = "Tasmania", AreaSqrKms = 68401, Capital = "Hobart" };
    
        states[4].SignificanCities = new string[] { "Melbourne", "Geelong", "Ballarat", "Bendigo", "Wodonga" };
        states[5].SignificanCities = new string[2];
        states[5].SignificanCities[0] = "Hobart";
        states[5].SignificanCities[1] = "Launceston";      
    }
    
    <table border="6" style="width: 660px" cellpadding="2" cellspacing="1">
        <tr>
            <td class="text-center"><b>Abbreviation</b></td>
            <td class="text-center"><b>State Name</b></td>
            <td class="text-center"><b>Area</b></td>
            <td><b>Capital</b></td>
            <td><b>Significan Cities</b></td>
        </tr>
        @for (int counter = 0; counter < states.Length - 1; counter++)
        {
            <tr>
                <td class="text-center">@states[counter].Abbreviation</td>
                <td>@states[counter].StateName</td>
                <td class="text-right">@states[counter].AreaSqrKms Km<sup>2</sup></td>
                <td>@states[counter].Capital</td>
                <td>
                    @for(int city = 0; city <= @states[counter].SignificanCities.Length - 1; city++)
                    {
                        @states[counter].SignificanCities[city]<br />;
                    }
                </td>
            </tr>
        }
    </table>
  5. This would produce:

    Accessing a Property of an Array Type

  6. Close the browser and return to your programming environment

Arrays of Objects and Methods

Passing an Array of Objects as Argument

As done for an array of a primitive type, you can pass an array of objects as arguments. You follow the same rules we reviewed; that is, in the parentheses of a method, enter the class name, the empty square brackets, and the name of the argument. Here is an example:

public class CompanyRecords
{
    public CompanyRecords(Employee[] employees)
    {
    }
}

You can then access each member of the argument and do what you judge necessary. For example, you can display the values that the argument is holding. To call a method that takes an array of objects, in its parentheses, just enter the name of the array. Here is an example:

public class CompanyRecords
{
    public CompanyRecords(Employee[] employees)
    {
         Employees = new Employee[]
         {
             new Employee(70128, "Justine Hearson", EmploymentStatus.PartTime, 10.62),
             new Employee(24835, "Bertha Hack", EmploymentStatus.FullTime, 18.94),
             new Employee(70128, "Frank Dennison", EmploymentStatus.Seasonal, 12.48),
             new Employee(24835, "Jeffrey Arndt", EmploymentStatus.PartTime, 16.05),
         };
    }
}

public class Exercise
{
    private void Present()
    {
        Employee[] Values = new Employee[4];

        CompanyRecords records = new CompanyRecords(Values);
    }
}

As stated for arrays of primitive types, an array of objects passed as argument is treated as a reference. You can use this characteristic of arrays to initialize the array. You can also indicate that the array is passed by reference by preceding its name with the ref keyword.

Returning an Array of Objects

An array of objects can be returned from a method. To indicate this when defining the method, first type the name of the class followed by square brackets. Here is an example:

public class CompanyRecords
{
    public Employee[] RegisterEmployees()
    {
    }
}

In the body of the method, you can take care of anythin you want. The major rule to follow is that, before exiting the method, you must return an array of the class indicated on the left side of the method name.

To use the method, you can simply call it. If you want, since the method returns an array, you can retrieve that list and store it in a local array for later use. Here is an example:

using System;
using static System.Environment;
using static System.Windows.Forms.MessageBox;

public enum EmploymentStatus
{
    FullTime,
    PartTime,
    Seasonal,
    Unknown
}

public class Employee
{
    public long EmployeeNumber { get; set; }
    public string EmployeeName { get; set; }
    public EmploymentStatus Status { get; set; }
    public double HourlySalary { get; set; }

    public Employee(long number, string name,
                    EmploymentStatus emplStatus, double salary)
    {
        EmployeeNumber = number;
        EmployeeName = name;
        Status = emplStatus;
        HourlySalary = salary;
    }
}

public class CompanyRecords
{
    public Employee[] RegisterEmployees()
    {
        Employee[] Employees = new Employee[]
        {
             new Employee(70128, "Justine Hearson", EmploymentStatus.PartTime, 10.62),
             new Employee(24835, "Bertha Hack", EmploymentStatus.FullTime, 18.94),
             new Employee(70128, "Frank Dennison", EmploymentStatus.Seasonal, 12.48),
             new Employee(24835, "Jeffrey Arndt", EmploymentStatus.PartTime, 16.05),
        };

        return Employees;
    }
}

public class Exercise
{
    public void Present()
    {
        CompanyRecords records = new CompanyRecords();

        Employee[] contractors = records.RegisterEmployees();
        records.PrepareRecords(ref contractors);
    }
}

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2008-2019, FunctionX Next