Home

Arrays and Classes

 

An Array of a Primitive Type as a Field

 

Introduction

As we have used them so far, 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
{
    private int[] Points;
}

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. Unlike C++, you can allocate memory for an array when declaring it. Here is an example:

public class CoordinateSystem
{
    private 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];
    }
}

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:

public class CoordinateSystem
{
    private int[] Points;

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

        Points[0] = 2;
        Points[1] = 5;
        Points[2] = 2;
        Points[3] = 8;
    }
}

Practical LearningPractical Learning: Introducing Arrays and Classes

  1. Start Microsoft Visual C# and create a Console Application named RentalProperties1
  2. To create a new class, in the Solution Explorer, right-click RenatlProperties1 -> Add -> Class...
  3. Set the Name to RentalProperty and press Enter
  4. Change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace RentalProperties1
    {
        public enum PropertyType { SingleFamily, Townhouse,
                                   Apartment, Unknown };
    
        public class RentalProperty
        {
            private long[] PropertyNumbers;
            private PropertyType[] Types;
            private short[] Bedrooms;
            private float[] Bathrooms;
            private double[] MonthlyRent;
    
            public RentalProperty()
            {
                PropertyNumbers = new long[] {
                    192873, 498730, 218502, 612739,
                    457834, 927439, 570520, 734059 };
    
                Types = new PropertyType[] {
                    PropertyType.SingleFamily, PropertyType.SingleFamily, 
                    PropertyType.Apartment, PropertyType.Apartment,
                    PropertyType.Townhouse, PropertyType.Apartment,
                    PropertyType.Apartment, PropertyType.Townhouse };
    
                Bedrooms = new short[] { 5, 4, 2, 1, 3, 1, 3, 4 };
    
                Bathrooms = new float[] { 3.50F, 2.50F, 1.00F, 1.00F,
                                          2.50F, 1.00F, 2.00F, 1.50F };
    
                MonthlyRent = new double[] {
                    2250.00D, 1885.00D, 1175.50D, 945.00D,
                    1750.50D, 1100.00D, 1245.95D, 1950.25D };
            }
        }
    }
  5. Save all and accept the suggested name of the project

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:

using System;

public class CoordinateSystem
{
    private int[] Points;

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

        Points[0] = 2;
        Points[1] = -5;
        Points[2] = 2;
        Points[3] = 8;
    }

    public void ShowPoints()
    {
        Console.WriteLine("Points Coordinates");
        Console.WriteLine("P({0}, {1})", Points[0], Points[1]);
        Console.WriteLine("Q({0}, {1})", Points[2], Points[3]);
    }
}

public class Exercise
{
    static int Main()
    {
        var Coordinates = new CoordinateSystem();

        Coordinates.ShowPoints();
        return 0;
    }
}

This would produce:

Points Coordinates
P(2, -5)
Q(2, 8)
Press any key to continue . . .

Practical LearningPractical Learning: Presenting an Array

  1. To show the values of the array, change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace RentalProperties1
    {
        public enum PropertyType { SingleFamily, Townhouse,
                                   Apartment, Unknown };
    
        public class RentalProperty
        {
            private long[] PropertyNumbers;
            private PropertyType[] Types;
            private short[] Bedrooms;
            private float[] Bathrooms;
            private double[] MonthlyRent;
    
            public RentalProperty()
            {
                PropertyNumbers = new long[] {
                    192873, 498730, 218502, 612739,
                    457834, 927439, 570520, 734059 };
    
                Types = new PropertyType[] {
                    PropertyType.SingleFamily, PropertyType.SingleFamily, 
                    PropertyType.Apartment, PropertyType.Apartment,
                    PropertyType.Townhouse, PropertyType.Apartment,
                    PropertyType.Apartment, PropertyType.Townhouse };
    
                Bedrooms = new short[] { 5, 4, 2, 1, 3, 1, 3, 4 };
    
                Bathrooms = new float[] { 3.50F, 2.50F, 1.00F, 1.00F,
                                          2.50F, 1.00F, 2.00F, 1.50F };
    
                MonthlyRent = new double[] {
                    2250.00D, 1885.00D, 1175.50D, 945.00D,
                    1750.50D, 1100.00D, 1245.95D, 1950.25D };
            }
    
            public void ShowListing()
            {
                Console.WriteLine("Properties Listing");
            Console.WriteLine("=============================================");
            Console.WriteLine("Prop #  Property Type Beds Baths Monthly Rent");
            Console.WriteLine("---------------------------------------------");
                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("{0}\t{1}\t{2}  {3:F}{4,12}",
                        PropertyNumbers[i], Types[i], Bedrooms[i],
                        Bathrooms[i], MonthlyRent[i]);
                }
            Console.WriteLine("=============================================");
            }
        }
    }
  2. Access the Program.cs file and change it as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace RentalProperties1
    {
        class Program
        {
            static void Main(string[] args)
            {
                RentalProperty Property = new RentalProperty();
    
                Property.ShowListing();
            }
        }
    }
  3. Execute the application to see the result
     
    Properties Listing
    =============================================
    Prop #  Property Type Beds Baths Monthly Rent
    ---------------------------------------------
    192873  SingleFamily    5  3.50        2250
    498730  SingleFamily    4  2.50        1885
    218502  Apartment       2  1.00      1175.5
    612739  Apartment       1  1.00         945
    457834  Townhouse       3  2.50      1750.5
    927439  Apartment       1  1.00        1100
    570520  Apartment       3  2.00     1245.95
    734059  Townhouse       4  1.50     1950.25
    =============================================
    Press any key to continue . . .
  4. Close the DOS window and return to your programming environment

Arrays and Methods

 

Introduction

Each member of an array holds a legitimate value. Therefore, 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.

The main purpose of using an array is to use various values grouped under one name. Still, an array is primarily a variable. As such, it can be passed to a method and it can be returned from a method.

An Array Passed as Argument

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

public class 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, 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 void ShowPoints(int[] Points)
    {
        Console.WriteLine("Points Coordinates");
        Console.WriteLine("P({0}, {1})", Points[0], Points[1]);
        Console.WriteLine("Q({0}, {1})", Points[2], Points[3]);
    }
}

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:

using System;

public class CoordinateSystem
{
    public void ShowPoints(int[] Points)
    {
        Console.WriteLine("Points Coordinates");
        Console.WriteLine("P({0}, {1})", Points[0], Points[1]);
        Console.WriteLine("Q({0}, {1})", Points[2], Points[3]);
    }
}

public class Exercise
{
    static int Main()
    {
        var Points = new int[] { -3, 3, 6, 3 };
        var Coordinates = new CoordinateSystem();

        Coordinates.ShowPoints(Points);
        return 0;
    }
}

This would produce:

Points Coordinates
P(-3, 3)
Q(6, 3)
Press any key to continue . . .

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

using System;

public class CoordinateSystem
{
    public void Initialize(int[] Coords)
    {
        Coords[0] = -4;
        Coords[1] = -2;
        Coords[2] = -6;
        Coords[3] =  3;
    }

    public void ShowPoints(int[] Points)
    {
        Console.WriteLine("Points Coordinates");
        Console.WriteLine("P({0}, {1})", Points[0], Points[1]);
        Console.WriteLine("Q({0}, {1})", Points[2], Points[3]);
    }
}

public class Exercise
{
    static int Main()
    {
        var System = new int[4];
        var Coordinates = new CoordinateSystem();

        Coordinates.Initialize(System);
        Coordinates.ShowPoints(System);

        return 0;
    }
}

This would produce:

Points Coordinates
P(-4, -2)
Q(-6, 3)
Press any key to continue . . .

Notice that the CreateNumbers() method receives an un-initialized array but returns it with new values. 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. Here is an example:

using System;

public class CoordinateSystem
{
    public void Initialize(ref int[] Coords)
    {
        Coords[0] = -4;
        Coords[1] = -2;
        Coords[2] = -6;
        Coords[3] = 3;
    }

    public void ShowPoints(int[] Points)
    {
        Console.WriteLine("Points Coordinates");
        Console.WriteLine("P({0}, {1})", Points[0], Points[1]);
        Console.WriteLine("Q({0}, {1})", Points[2], Points[3]);
    }
}

public class Exercise
{
    static int Main()
    {
        var System = new int[4];
        var Coordinates = new CoordinateSystem();

        Coordinates.Initialize(ref System);
        Coordinates.ShowPoints(System);

        return 0;
    }
}

Instead of just one, you can create a method that receive 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.

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

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

public class 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;

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

        return Coords;
    }

    public void ShowPoints(int[] Points)
    {
        Console.WriteLine("Points Coordinates");
        Console.WriteLine("P({0}, {1})", Points[0], Points[1]);
        Console.WriteLine("Q({0}, {1})", Points[2], Points[3]);
    }
}

public class Exercise
{
    static int Main()
    {
        var System = new int[4];
        var Coordinates = new CoordinateSystem();

        System = Coordinates.Initialize();
        Coordinates.ShowPoints(System);

        return 0;
    }
}

The method could also be called as follows:

public class Exercise
{
    static int Main()
    {
        var Coordinates = new CoordinateSystem();

        var System = Coordinates.Initialize();
        Coordinates.ShowPoints(System);

        return 0;
    }
}

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

Main()'s Argument

  

Introduction

When a program starts, it looks for an entry point. This is the role of the Main() method. In fact, a program, that is an executable program, starts by, and stops with, the Main() method. The way this works is that, at the beginning, the compiler looks for a method called Main. If it doesn't find it, it produces an error. If it finds it, it enters the Main() method in a top-down approach, starting just after the opening curly bracket. If it finds a problem and judges that it is not worth continuing, it stops and lets you know. If, or as long as, it doesn't find a problem, it continues line after line, with the option to even call or execute a method in the same file or in another file. This process continues to the closing curly bracket "}". Once the compiler finds the closing bracket, the whole program has ended and stops.

If you want the user to provide additional information when executing your program, you can take care of this in the Main() method. Consider the following code written in a file saved as Exercise.cs:

using System;

public class Exercise
{
    static int Main()
    {
	string FirstName = "James";
     	string LastName  = "Weinberg";
        double WeeklyHours = 36.50;
	double HourlySalary = 12.58;
	   
	string FullName = LastName + ", " + FirstName;
	double WeeklySalary = WeeklyHours * HourlySalary;

	Console.WriteLine("Employee Payroll");
	Console.WriteLine("Full Name:    {0}", FullName);
	Console.WriteLine("WeeklySalary: {0}", WeeklySalary.ToString("C"));
	return 0;
    }
}

To execute the application, at the Command Prompt and after Changing to the Directory that contains the file, you would type

csc Exercise.cs

and press Enter. To execute the program, you would type the name Exercise and press Enter. The program would then prompt you for the information it needs.

Command Request from Main()

To compile a program, you would simply type the csc command at the command prompt. Then, to execute a program, you would type its name at the prompt. If you distribute a program, you would tell the user to type the name of the program at the command prompt. In some cases, you may want the user to type additional information besides the name of the program. To request additional information from the user, you can pass a string argument to the Main() method. The argument should be passed as an array and make sure you provide a name for the argument. Here is an example:

using System;

class ObjectName
{
    static int Main(string[] args)
    {
        return 0;
    }
}

The reason you pass the argument as an array is so you can use as many values as you judge necessary. To provide values at the command prompt, the user types the name of the program followed by each necessary value. Here is an example:

Command Line

The values the user would provide are stored in a zero-based array without considering the name of the program. The first value (that is, after the name of the program) is stored at index 0, the second at index 1, etc. Based on this, the first argument is represented by args[0], the second is represented by args[1], etc.

Each of the values the user types is a string. If any one of them is not a string, you should/must convert/cast its string first to the appropriate value. Consider the following source code:

using System;

namespace CSharpLessons
{
    public class Exercise
    {
	static int Main(string[] Argument)
	{
	    string FirstName;
     	    string LastName;
                    Double WeeklyHours;
	    Double HourlySalary;
	   
	    FirstName    = Argument[0];
            LastName     = Argument[1];
	    WeeklyHours  = Double.Parse(Argument[2]);
	    HourlySalary = Double.Parse(Argument[3]);

	    string FullName = LastName + ", " + FirstName;
	    Double WeeklySalary = WeeklyHours * HourlySalary;

	    Console.WriteLine("Employee Payroll");
	    Console.WriteLine("Full Name:       {0}", FullName);
	    Console.WriteLine("WeeklySalary: {0}", WeeklySalary.ToString("C"));

	    return 0;
	}
    }
}

To compile it at the Command Prompt, after switching to the directory that contains the file, you would type

csc Exercise.cs

and press Enter. To execute the program, you would type Exercise followed by a first name, a last name, and two decimal values. An example would be Exercise Catherine Engolo 42.50 20.48

Command Line

 

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;

public enum EmploymentStatus
{
    FullTime,
    PartTime,
    Unknown
};
public class Employee
{
    private long emplNbr;
    private string name;
    private EmploymentStatus st;
    private double wage;

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

Practical LearningPractical Learning: Introducing Arrays of Objects

  1. Create a new Console Application named RentalProperties2
  2. To create a new class, in the Solution Explorer, right-click RenatlProperties1 -> Add -> Class...
  3. Set the Name to RentalProperty and press Enter
  4. Change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace RentalProperties2
    {
        public enum PropertyType
        {
            SingleFamily, Townhouse,
            Apartment, Unknown
        };
    
        public class RentalProperty
        {
            private long nbr;
            private PropertyType tp;
            private short bd;
            private float bt;
            private double rnt;
    
            public RentalProperty()
            {
                nbr = 0;
                tp = PropertyType.Unknown;
                bd = 0;
                bt = 0.0F;
                rnt = 0D;
            }
    
            public RentalProperty(long PropNbr, PropertyType Type,
                                  short Beds, float Baths, double Rent)
            {
                PropNbr = nbr;
                Type = PropertyType.Unknown;
                Beds = bd;
                Baths = bt;
                Rent = rnt;
            }
    
            public long PropertyNumber
            {
                get { return nbr; }
                set { nbr = value; }
            }
    
            public PropertyType TypeOfProperty
            {
                get { return tp; }
                set { tp = value; }
            }
    
            public short Bedrooms
            {
                get { return bd; }
                set { bd = value; }
            }
    
            public float Bathrooms
            {
                get { return bt; }
                set { bt = value; }
            }
    
            public double MonthlyRent
            {
                get { return rnt; }
                set { rnt = value; }
            }
        }
    }
  5. Save all and accept the suggested name of the project

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:

public static class Exercise
{
    static void Main(string[] args)
    {
        Employee[] StaffMembers = new Employee[3];

        return 0;
    }
}

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

public static class Exercise
{
    static void Main(string[] args)
    {
        var StaffMembers = new Employee[3];

        return 0;
    }
}

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:

public static class Exercise
{
    static void Main(string[] args)
    {
        var 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;

        return 0;
    }
}

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;

public enum EmploymentStatus
{
    FullTime,
    PartTime,
    Unknown
};

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

    public Employee()
    {
    }

    public Employee(long Number, string Name,
                    EmploymentStatus EStatus, double Salary)
    {
        emplNbr = Number;
        name = Name;
        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; }
    }
}

public static class Exercise
{
    static void Main(string[] args)
    {
        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)
        };

        return 0;
    }
}

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:

public static class Exercise
{
    static void Main(string[] args)
    {
        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)
        };

        return 0;
    }
}

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:

public static class Exercise
{
    static void Main(string[] args)
    {
        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)
        };

        Console.WriteLine("Employee Record");
        Console.WriteLine("---------------------------");
        Console.WriteLine("Employee #: {0}", StaffMembers[2].EmployeeNumber);
        Console.WriteLine("Full Name:  {0}", StaffMembers[2].EmployeeName);
        Console.WriteLine("Status:     {0}", StaffMembers[2].Status);
        Console.WriteLine("Hourly Wage {0}", StaffMembers[2].HourlySalary);
        Console.WriteLine("---------------------------\n");

        return 0;
    }
}

This would produce:

Employee Record
---------------------------
Employee #: 42963
Full Name:  Sharon Culbritt
Status:     PartTime
Hourly Wage 10.95
---------------------------

Press any key to continue . . .

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

In the same way, you can use a for loop to access all members of the array using their index. Here is an example:

public static class Exercise
{
    static void Main(string[] args)
    {
        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)
        };

        Console.WriteLine("Employees Records");
        Console.WriteLine("==========================");
        for (int i = 0; i < 3; i++)
        {
            Console.WriteLine("Employee #: {0}", StaffMembers[i].EmployeeNumber);
            Console.WriteLine("Full Name:  {0}", StaffMembers[i].EmployeeName);
            Console.WriteLine("Status:     {0}", StaffMembers[i].Status);
            Console.WriteLine("Hourly Wage {0}", StaffMembers[i].HourlySalary);
            Console.WriteLine("---------------------------");
        }

        return 0;
    }
}

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

public static class Exercise
{
    static void Main(string[] args)
    {
        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)
        };

        Console.WriteLine("Employees Records");
        Console.WriteLine("==========================");
        foreach(var Member in StaffMembers)
        {
            Console.WriteLine("Employee #: {0}", Member.EmployeeNumber);
            Console.WriteLine("Full Name:  {0}", Member.EmployeeName);
            Console.WriteLine("Status:     {0}", Member.Status);
            Console.WriteLine("Hourly Wage {0}", Member.HourlySalary);
            Console.WriteLine("---------------------------");
        }

        return 0;
    }
}

This would produce:

Employees Records
==========================
Employee #: 20204
Full Name:  Harry Fields
Status:     FullTime
Hourly Wage 16.85
---------------------------
Employee #: 92857
Full Name:  Jennifer Almonds
Status:     FullTime
Hourly Wage 22.25
---------------------------
Employee #: 42963
Full Name:  Sharon Culbritt
Status:     PartTime
Hourly Wage 10.95
---------------------------
Press any key to continue . . .

Practical LearningPractical Learning: Using an Array of Objects

  1. Access the Program.cs file and change it file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace RentalProperties2
    {
        public class Program
        {
            static void Main(string[] args)
            {
                RentalProperty[] Properties = new RentalProperty[8];
    
                Properties[0] = new RentalProperty();
                Properties[0].PropertyNumber = 192873;
                Properties[0].TypeOfProperty = PropertyType.SingleFamily;
                Properties[0].Bedrooms = 5;
                Properties[0].Bathrooms = 3.50F;
                Properties[0].MonthlyRent = 2250.00D;
                Properties[1] = new RentalProperty();
                Properties[1].PropertyNumber = 498730;
                Properties[1].TypeOfProperty = PropertyType.SingleFamily;
                Properties[1].Bedrooms = 4;
                Properties[1].Bathrooms = 2.50F;
                Properties[1].MonthlyRent = 1885.00D;
                Properties[2] = new RentalProperty();
                Properties[2].PropertyNumber = 218502;
                Properties[2].TypeOfProperty = PropertyType.Apartment;
                Properties[2].Bedrooms = 2;
                Properties[2].Bathrooms = 1.00F;
                Properties[2].MonthlyRent = 1175.50D;
                Properties[3] = new RentalProperty();
                Properties[3].PropertyNumber = 612739;
                Properties[3].TypeOfProperty = PropertyType.Apartment;
                Properties[3].Bedrooms = 1;
                Properties[3].Bathrooms = 1.00F;
                Properties[3].MonthlyRent = 945.00D;
                Properties[4] = new RentalProperty();
                Properties[4].PropertyNumber = 457834;
                Properties[4].TypeOfProperty = PropertyType.Townhouse;
                Properties[4].Bedrooms = 3;
                Properties[4].Bathrooms = 2.50F;
                Properties[4].MonthlyRent = 1750.50D;
                Properties[5] = new RentalProperty();
                Properties[5].PropertyNumber = 927439;
                Properties[5].TypeOfProperty = PropertyType.Apartment;
                Properties[5].Bedrooms = 1;
                Properties[5].Bathrooms = 1.00F;
                Properties[5].MonthlyRent = 1100.00D;
                Properties[6] = new RentalProperty();
                Properties[6].PropertyNumber = 570520;
                Properties[6].TypeOfProperty = PropertyType.Apartment;
                Properties[6].Bedrooms = 3;
                Properties[6].Bathrooms = 2.00F;
                Properties[6].MonthlyRent = 1245.95D;
                Properties[7] = new RentalProperty();
                Properties[7].PropertyNumber = 734059;
                Properties[7].TypeOfProperty = PropertyType.Townhouse;
                Properties[7].Bedrooms = 4;
                Properties[7].Bathrooms = 1.50F;
                Properties[7].MonthlyRent = 1950.25D;
    
                Console.WriteLine("Properties Listing");
            Console.WriteLine("=============================================");
            Console.WriteLine("Prop #  Property Type Beds Baths Monthly Rent");
            Console.WriteLine("---------------------------------------------");
                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("{0}\t{1}\t{2}  {3:F}{4,12}",
                                      Properties[i].PropertyNumber,
                                      Properties[i].TypeOfProperty,
                                      Properties[i].Bedrooms, 
    				  Properties[i].Bathrooms,
                                      Properties[i].MonthlyRent);
                }
            Console.WriteLine("=============================================");
            }
        }
    }
  2. Execute the application to see the result
     
    Properties Listing
    =============================================
    Prop #  Property Type Beds Baths Monthly Rent
    ---------------------------------------------
    192873  SingleFamily    5  3.50        2250
    498730  SingleFamily    4  2.50        1885
    218502  Apartment       2  1.00      1175.5
    612739  Apartment       1  1.00         945
    457834  Townhouse       3  2.50      1750.5
    927439  Apartment       1  1.00        1100
    570520  Apartment       3  2.00     1245.95
    734059  Townhouse       4  1.50     1950.25
    =============================================
    Press any key to continue . . .
  3. Close the DOS window and return to your programming environment

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:

public class CompanyRecords
{
    Employee[] Employees = new Employee[2];
}

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:

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 member, you can get to its fields or properties. Here is an example:

using System;

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 Name,
                    EmploymentStatus EStatus, double Salary)
    {
        emplNbr = Number;
        name = Name;
        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; }
    }
}

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),
         };
    }

    public void ShowRecords()
    {
        Console.WriteLine("Employees Records");
        Console.WriteLine("==========================");

        foreach (var Member in Employees)
        {
            Console.WriteLine("Employee #: {0}", Member.EmployeeNumber);
            Console.WriteLine("Full Name:  {0}", Member.EmployeeName);
            Console.WriteLine("Status:     {0}", Member.Status);
            Console.WriteLine("Hourly Wage {0}", Member.HourlySalary);
            Console.WriteLine("---------------------------");
        }
    }
}

public static class Exercise
{
    static void Main(string[] args)
    {
        var Records = new CompanyRecords();
        Records.ShowRecords();

        return 0;
    }
}

This would produce:

Employees Records
==========================
Employee #: 70128
Full Name:  Justine Hearson
Status:     PartTime
Hourly Wage 10.62
---------------------------
Employee #: 24835
Full Name:  Bertha Hack
Status:     FullTime
Hourly Wage 18.94
---------------------------
Employee #: 70128
Full Name:  Frank Dennison
Status:     Seasonal
Hourly Wage 12.48
---------------------------
Employee #: 24835
Full Name:  Jeffrey Arndt
Status:     PartTime
Hourly Wage 16.05
---------------------------
Press any key to continue . . .

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 static class Exercise
{
    static void Main(string[] args)
    {
        var Values = new Employee[4];

        CompanyRecords Records = new CompanyRecords(Values);
        Records.ShowRecords();

        return 0;
    }
}

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:

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. If you want, since the method returns an array, you can retrieve that series and store it in a local array value for later use. Here is an example:

using System;

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 Name,
                    EmploymentStatus EStatus, double Salary)
    {
        emplNbr = Number;
        name = Name;
        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; }
    }
}

public class CompanyRecords
{
    public CompanyRecords()
    {
    }
    
    public Employee[] RegisterEmployees()
    {
        var 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 void ShowRecords(ref Employee[] Records)
    {
        Console.WriteLine("Employees Records");
        Console.WriteLine("==========================");

        foreach (var Staff in Records)
        {
            Console.WriteLine("Employee #: {0}", Staff.EmployeeNumber);
            Console.WriteLine("Full Name:  {0}", Staff.EmployeeName);
            Console.WriteLine("Status:     {0}", Staff.Status);
            Console.WriteLine("Hourly Wage {0}", Staff.HourlySalary);
            Console.WriteLine("---------------------------");
        }
    }
}

public static class Exercise
{
    static void Main(string[] args)
    {
        var Records = new CompanyRecords();

        var Contractors = Records.RegisterEmployees();
        Records.ShowRecords(ref Contractors);

        return 0;
    }
}

Practical LearningPractical Learning: Using Array of Objects With Methods

  1. To apply what we learned in the last few sections, change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace RentalProperties2
    {
        public class Program
        {
            private static void ShowProperties(RentalProperty[] Properties)
            {
                Console.WriteLine("Properties Listing");
                Console.WriteLine("=============================================");
                Console.WriteLine("Prop #  Property Type Beds Baths Monthly Rent");
                Console.WriteLine("---------------------------------------------");
                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("{0}\t{1}\t{2}  {3:F}{4,12}",
                                      Properties[i].PropertyNumber,
                                      Properties[i].TypeOfProperty,
                                      Properties[i].Bedrooms, 
    				  Properties[i].Bathrooms,
                                      Properties[i].MonthlyRent);
                }
                Console.WriteLine("=============================================");
            }
    
            private static RentalProperty[] CreateListing()
            {
                RentalProperty[] HousesToRent = new RentalProperty[8];
    
                HousesToRent[0] = new RentalProperty();
                HousesToRent[0].PropertyNumber = 192873;
                HousesToRent[0].TypeOfProperty = PropertyType.SingleFamily;
                HousesToRent[0].Bedrooms = 5;
                HousesToRent[0].Bathrooms = 3.50F;
                HousesToRent[0].MonthlyRent = 2250.00D;
                HousesToRent[1] = new RentalProperty();
                HousesToRent[1].PropertyNumber = 498730;
                HousesToRent[1].TypeOfProperty = PropertyType.SingleFamily;
                HousesToRent[1].Bedrooms = 4;
                HousesToRent[1].Bathrooms = 2.50F;
                HousesToRent[1].MonthlyRent = 1885.00D;
                HousesToRent[2] = new RentalProperty();
                HousesToRent[2].PropertyNumber = 218502;
                HousesToRent[2].TypeOfProperty = PropertyType.Apartment;
                HousesToRent[2].Bedrooms = 2;
                HousesToRent[2].Bathrooms = 1.00F;
                HousesToRent[2].MonthlyRent = 1175.50D;
                HousesToRent[3] = new RentalProperty();
                HousesToRent[3].PropertyNumber = 612739;
                HousesToRent[3].TypeOfProperty = PropertyType.Apartment;
                HousesToRent[3].Bedrooms = 1;
                HousesToRent[3].Bathrooms = 1.00F;
                HousesToRent[3].MonthlyRent = 945.00D;
                HousesToRent[4] = new RentalProperty();
                HousesToRent[4].PropertyNumber = 457834;
                HousesToRent[4].TypeOfProperty = PropertyType.Townhouse;
                HousesToRent[4].Bedrooms = 3;
                HousesToRent[4].Bathrooms = 2.50F;
                HousesToRent[4].MonthlyRent = 1750.50D;
                HousesToRent[5] = new RentalProperty();
                HousesToRent[5].PropertyNumber = 927439;
                HousesToRent[5].TypeOfProperty = PropertyType.Apartment;
                HousesToRent[5].Bedrooms = 1;
                HousesToRent[5].Bathrooms = 1.00F;
                HousesToRent[5].MonthlyRent = 1100.00D;
                HousesToRent[6] = new RentalProperty();
                HousesToRent[6].PropertyNumber = 570520;
                HousesToRent[6].TypeOfProperty = PropertyType.Apartment;
                HousesToRent[6].Bedrooms = 3;
                HousesToRent[6].Bathrooms = 2.00F;
                HousesToRent[6].MonthlyRent = 1245.95D;
                HousesToRent[7] = new RentalProperty();
                HousesToRent[7].PropertyNumber = 734059;
                HousesToRent[7].TypeOfProperty = PropertyType.Townhouse;
                HousesToRent[7].Bedrooms = 4;
                HousesToRent[7].Bathrooms = 1.50F;
                HousesToRent[7].MonthlyRent = 1950.25D;
    
                return HousesToRent;
            }
    
            static void Main(string[] args)
            {
                RentalProperty[] Properties = CreateListing();
    
                ShowProperties(Properties);
            }
        }
    }
  2. Execute the application to see the result 
  3. Close the DOS window and return to your programming environment

Arrays and Delegates

 

Introduction

While a regular method can be used to return an array, you can use the features of a delegate to return an array of methods or to take an array of methods as arguments. Of course before proceeding, you must first create the necessary delegate. Here is an example:

using System;

delegate double Measure(double R);

public static class Program
{
    static int Main(string[] args)
    {
        return 0;
    }
}

Before creating the array, you must first know or have the methods you would be referring to. These methods must have a similar signature. This means that they must return the same type of value, they must have the same number of arguments and they must  have the  same type(s) of argument(s), if any. Here are examples of such functions:

using System;

delegate double Measure(double R);

public class Circle
{
    const double PI = 3.14159;

    double Diameter(double Radius)
    {
        return Radius * 2;
    }

    double Circumference(double Radius)
    {
        return Diameter(Radius) * PI;
    }

    double Area(double Radius)
    {
        return Radius * Radius * PI;
    }
}

public static class Program
{
    static void Main(string[] args)    {
        return 0;
    }
}

An Array of Delegates

To create an array of delegates, declare a normal array as we have done so far. You can initialize each member using its index and calling the corresponding method. This can be done as follows:

using System;

delegate double Measure(double R);

public class Circle
{
    const double PI = 3.14159;

    public double Diameter(double Radius)
    {
        return Radius * 2;
    }

    public double Circumference(double Radius)
    {
        return Diameter(Radius) * PI;
    }

    public double Area(double Radius)
    {
        return Radius * Radius * PI;
    }
}

public static class Program
{
    static void Main(string[] args)    {
        double R = 12.55;
        Circle circ = new Circle();
        Measure[] Calc = new Measure[3];

        Calc[0] = new Measure(circ.Diameter);
        double D = Calc[0](R);
        Calc[1] = new Measure(circ.Circumference);
        double C = Calc[1](R);
        Calc[2] = new Measure(circ.Area);
        double A = Calc[2](R);

        Console.WriteLine("Circle Characteristics");
        Console.WriteLine("Diameter:      {0}", D);
        Console.WriteLine("Circumference: {0}", C);
        Console.WriteLine("Area:          {0}\n", A);

        return 0;
    }
}

You can also list the members of the array when creating it. After creating the array, you can retrieve its value and store it in a variable. Here is an example:

public static class Program
{
    static void Main(string[] args)    {
        double R = 12.55;
        Circle circ = new Circle();
        Measure[] Calc = new Measure[]
        {
            new Measure(circ.Diameter),
            new Measure(circ.Circumference),
            new Measure(circ.Area)
        };
        
        double D = Calc[0](R);
        double C = Calc[1](R);
        double A = Calc[2](R);

        Console.WriteLine("Circle Characteristics");
        Console.WriteLine("Diameter:      {0}", D);
        Console.WriteLine("Circumference: {0}", C);
        Console.WriteLine("Area:          {0}\n", A);

        return 0;
    }
}

The above code could also be written as follows:

public static class Program
{
    static void Main(string[] args)
    {
        double R = 12.55;
        Circle circ = new Circle();
        Measure[] Calc = new Measure[]
        {
            new Measure(circ.Diameter),
            new Measure(circ.Circumference),
            new Measure(circ.Area)
        };
        
        Console.WriteLine("Circle Characteristics");
        Console.WriteLine("Diameter:      {0}", Calc[0](R));
        Console.WriteLine("Circumference: {0}", Calc[1](R));
        Console.WriteLine("Area:          {0}\n", Calc[2](R));

        return 0;
    }
}

This would produce:

Circle Characteristics
Diameter:      25.1
Circumference: 78.8539
Area:          494.808

 

 

Previous Copyright © 2008-2011 FunctionX Next