Home

Arrays and Classes

 

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:

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

/// <summary>
/// Summary description for CoordinateSystem
/// </summary>
public class CoordinateSystem
{
    private int[] points;

    public CoordinateSystem()
    {
    }
}

Like any field, when an array has been declared as a member variable, 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 the initialized variable. This also means that you don't have to pass the array as argument nor do you have to explicitly return it from a method.

After or when declaring an array, you must make sure you allocate memory for it prior to using. You can allocate memory for an array when declaring it. Here is an example:

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

/// <summary>
/// Summary description for CoordinateSystem
/// </summary>
public class CoordinateSystem
{
    private int[] points = new int[4];

    public CoordinateSystem()
    {
    }
}

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

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

/// <summary>
/// Summary description for CoordinateSystem
/// </summary>
public class CoordinateSystem
{
    private int[] points;

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

If you plan to use the array as soon as the program is running, you can initialize it using a constructor or a method that you know would be called before the array can be used. Here is an example:

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

/// <summary>
/// Summary description for CoordinateSystem
/// </summary>
public class CoordinateSystem
{
    private 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, 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.

Arrays and Methods

 

Introduction

Each member of an array holds a legitimate value. You can pass a single member of an array as argument. You can pass the name of the array variable with the accompanying index to a method.

Returning an Array From a Method

You can create a method that takes an array as argument and returns another array as argument.

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

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

/// <summary>
/// Summary description for CoordinateSystem
/// </summary>
public class CoordinateSystem
{
    public 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 variable. 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:

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

/// <summary>
/// Summary description for CoordinateSystem
/// </summary>
public class CoordinateSystem
{
    public CoordinateSystem()
    {
    }

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

        return Coords;
    }
}

When a method returns an array, that method can be assigned to an array declared locally when you want to use it. Remember to initialize a variable with such a method only if the variable is an array. 

Here is an example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var system = new int[4];
        var coordinates = new CoordinateSystem();

        system = coordinates.Initialize();
    }
}

If you initialize an array variable with a method that doesn't return an array, you would receive an error.

An Array Passed as Argument

Like a regular variable, an array can be passed as argument. In the parentheses of a method, provide the data type, the empty square brackets, and the name of the argument. Here is an example:

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

/// <summary>
/// Summary description for CoordinateSystem
/// </summary>
public class CoordinateSystem
{
    public CoordinateSystem()
    {

    }

    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 can be. The simplest way you can use an array is to display the values of its members.

To call a method that takes an array as argument, simply type the name of the array in the parentheses of the called method.

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. To enforce the concept of passing a variable by reference, you can also accompany an array argument with the ref keyword, both when defining the method and when calling it.

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. There is no rule that sets some restrictions.

You can also create a method that takes one or more arrays as argument(s) and returns a regular value of a primitive type.

An Array of Objects

 

Introduction

As done for primitive types, 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 or you can create your own class. Here is an example:

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

/// <summary>
/// Summary description for Employee
/// </summary>

public enum EmploymentStatus
{
    FullTime,
    PartTime,
    Unknown
};

public class Employee
{
    private long emplNbr;
    private string name;
    private EmploymentStatus st;
    private double wage;

    public Employee()
    {
    }

    public long EmployeeNumber
    {
        get { return emplNbr; }
        set { emplNbr = value; }
    }

    public string EmployeeName
    {
        get { return name; }
        set { name = value; }
    }

    public EmploymentStatus Status
    {
        get { return st; }
        set { st = value; }
    }

    public double HourlySalary
    {
        get { return wage; }
        set { wage = value; }
    }
}

Creating an Array of Objects

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Employee[] StaffMembers = new Employee[3];
    }
}

You can also use the var keyword to create the array but omit the first square brackets. Here is an example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var staffMembers = new Employee[3];
    }
}

Initializing an Array of Objects

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        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;
    }
}

As an alternative, you can also initialize each member of the array when creating it. To do this, before the semi-colon of creating the array, open the curly brackets, allocate memory for each member and specify the values of each field. To do this, you must use a constructor that takes each member you want to initialize, as argument. Here is an example:

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

/// <summary>
/// Summary description for Employee
/// </summary>

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

public class Employee
{
    private long emplNbr;
    private string name;
    private EmploymentStatus st;
    private double wage;

    public Employee()
    {
    }

    public Employee(long number, string nm,
                    EmploymentStatus eStatus, double salary)
    {
        emplNbr = number;
        name    = nm;
        st      = eStatus;
        wage    = salary;
    }

    public long EmployeeNumber
    {
        get { return emplNbr; }
        set { emplNbr = value; }
    }

    public string EmployeeName
    {
        get { return name; }
        set { name = value; }
    }

    public EmploymentStatus Status
    {
        get { return st; }
        set { st = value; }
    }

    public double HourlySalary
    {
        get { return wage; }
        set { wage = value; }
    }
}

-----------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var 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 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:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        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)
        };
    }
}
 
 

Accessing the Members of the Array

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:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var 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)
        };

        Response.Write("<pre><b>Employee Record</b><hr></hr>");
        Response.Write("<br />Employee    #: " + staffMembers[2].EmployeeNumber);
        Response.Write("<br />Full Name:  #: " + staffMembers[2].EmployeeName);
        Response.Write("<br />Status:     #: " + staffMembers[2].Status);
        Response.Write("<br />Hourly Wage #: " + 
			staffMembers[2].HourlySalary + "</pre>");
    }
}

This would produce:

Array

Once again, remember that the index you use must be higher than 0 but lower than the number of members - 1. Otherwise, you would get an IndexOutRangeException exception.

In the same way, you can use a for loop to access all members of the array using their index. To access each member of the array, you can use the foreach operator that allows you to use a name for each member and omit the square brackets.

A Class Array as a Field

 

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:

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

/// <summary>
/// Summary description for CompanyRecords
/// </summary>
public class CompanyRecords
{
    Employee[] Employees = new Employee[2];

    public CompanyRecords()
    {
    }
}

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.

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:

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

/// <summary>
/// Summary description for CompanyRecords
/// </summary>
public class CompanyRecords
{
    Employee[] Employees = new Employee[2];

    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:

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

/// <summary>
/// Summary description for CompanyRecords
/// </summary>
public class CompanyRecords
{
    Employee[] Employees = new Employee[2];

    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 member, you can get to its fields or properties.

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:

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

/// <summary>
/// Summary description for CompanyRecords
/// </summary>
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.

As stated for an array of primitive type, 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:

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

/// <summary>
/// Summary description for CompanyRecords
/// </summary>
public class CompanyRecords
{
    public Employee[] RegisterEmployees()
    {
    }
}

In the body of the method, you can take care of any assignment 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 series and store it in a local array for later use.

 

 

 

   
 

Previous Copyright © 2009-2016, FunctionX, Inc. Home