Introduction to the Class to Manage Arrays

Overview

To assist with the use and management of arrays, you can combine the array features of the C# language and support from the .NET Framework. As mentioned already, to support arrays, the .NET Framework provides the Array class that is defined in the System namespace of the mscorlib.dll assembly.

When you create an array in C# code, whether an array of primitive values or an array of objects, you are in fact declaring a variable of type Array. Based on this, since an array variable is an object of a class type, you can use the characteristics of the Array class to create an array and/or to manipulate the values stored in the variable. You can create an array using any of the techniques we saw in the previous lessons, or you can use the Array class.

Practical LearningPractical Learning: Introducing Arrays and Classes

  1. Start Microsoft Visual Studio and create a new Windows Forms application named CountriesStatistics6
  2. In the Solution Explorer, right-click CountriesStatistics6 -> Add -> New Item...
  3. In the left frame of the Add New Item dialog box, click Code and, in the middle frame, click Interface
  4. Change the Name to Abbreviated
  5. Click Add
  6. Create a string-based property as follows:
    namespace CountriesStatistics6
    {
        public interface IAbbreviated
        {
            string Abbreviation { get; set; }
        }
    }
    
  7. In the Solution Explorer, right-click CountriesStatistics6 -> Add -> New Item...
  8. In the middle list of the Add New Item dialog box, make sure Interface is selected.
    Change the file name to GovernmentEntity
  9. Click Add
  10. Change the document as follows:
    namespace CountriesStatistics6
    {
        public interface IGovernmentEntity
        {
            string Name    { get; set; }
            int    Area    { get;      }
            string Capital { get; set; }
        }
    }
  11. In the Solution Explorer, right-click CountriesStatistics6 -> Add -> Class...
  12. Change the file Name to Region as the Name of the class
  13. Click Add
  14. Change the document as follows:
    namespace CountriesStatistics6
    {
        public class Region
        {
            public string Designation { get; set; }
            public string Description { get; set; }
        }
    }
  15. In the Solution Explorer, right-click Models -> Add -> Class...
  16. Type State as the name of the file
  17. Press Enter
  18. Change the class as follows:
    namespace CountriesStatistics6
    {
        public class State : IGovernmentEntity, IAbbreviated
        {
            // From the IAbbreviated interface
            public string Abbreviation { get; set; }
    
            // From the IGovernmentEntity interface
            public string Name         { get; set; }
            public int    Area         { get; set; }
            public string Capital      { get; set; }
    
            // New Properties
            public string StateName    => Name;
            public int    AreaSqrMiles => Area;
            public int    AreaSqrKms   { get; set; }
            public Region Region       { get; set; }
            
            public override bool Equals(object obj)
            {
                State stt = (State)obj;
                
                if (stt.Name == Name)
                    return true;
                
                return false;
            }
            
            public override int GetHashCode()
            {
                return base.GetHashCode();
            }
        }
    }
  19. In the Solution Explorer, right-click CountriesStatistics6 -> Add -> Class...
  20. Type Federation
  21. Click Add
  22. Change the document as follows:
    namespace CountriesStatistics6
    {
        public class Federation : State
        {
            public int AdmissionUnionOrder { get; set; }
        }
    }
  23. In the Solution Explorer, double-click Form1.cs to access the form
  24. Design the form as follows:

    Doing Something While a Condition is True

    Control (Name) Text TextAlign
    Label   United States of America Font: Georgia, 20.25pt, style=Bold
    Label   ____________________________________  
    ListView lvwStates  
    View:          Details
    GridLines:     True
    FullRowSelect: True
    Anchor: Top, Bottom, Left, Right

    List View Columns

    (Name) Text TextAlign Width
    colNumber #   25
    colAbbreviation Abbrv Center 40
    colStateName State Name   100
    colAreaSqrKms Area (Sqr Kms) Right 90
    colAreaSqrMiles Area (Sqr Ml) Right 80
    colAdmissionToFederation Adm to Fedrt (Order) Center 130
    colCapital Capital   80
    colRegion Region   120
  25. Right-click the form and click View Code

Creating an Array

To assist you with creating an array, the Array class is equipped with a method named CreateInstance() that comes in various versions. To create a one-dimensional array whose members are zero-based, you can use the following version:

public static Array CreateInstance(Type elementType, int length);

The first argument is used to specify the type of array you want to create. You are allowed to create an array of any type, that is, an array of primitive values or an array of objects. The first argument is declared as Type. This means that it can be anything. For this reason, you can use the typeof operator to cast your type. Therefore, pass the type or the class in the parentheses of the typeof operator.

The second argument specifies the number of members of the array. Using the Array class, you can create an array as follows:

using System;

public class Exercise
{
    public static int Main(string[] args)
    {
        Array numbers = Array.CreateInstance(typeof(double), length);

        return 10;
    }
}

You can also use the var or the dynamic keyword to declare the variable. Here is an example:

var numbers = Array.CreateInstance(typeof(double), 5);

The Length of an Array

We know that if you declare a variable for an array but don't initialize it, you must specify the number of elements of the array. Here is an example:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        double[] numbers = new double[5];

        return 100;
    }
}

If you use the Array class to create an array, you must pass this constant integer as the second argument of the CreateInstance() method from the the above version. Here is an example:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        var numbers = Array.CreateInstance(typeof(double), 5);

        return 1000;
    }
}

If the array exists already, that is, if you have already created the array or you are using an array created by someone else, to find out the number of items it contains, you can access its Length property. Therefore, the length of an array is the number of elements it contains.

Alternatively, you can call the Array.GetLength() method. Its syntax is:

public int GetLength(int dimension);

For a one-dimensional array, you must pass the argument as 0. This method returns an integer that represents the number of items in the array.

Practical LearningPractical Learning: Creating an Array

The Rank of an Array

We have seen that the square brackets are used to specify that you are declaring an array. If you are creating a one-dimensional array, we saw that you could type a number in the square bracket. If you are creating a two-dimensional array, you type two numbers separated by a comma in the second pair of square brackets. Each number, whether it is one, two, or more is a placeholder for what is referred to as a dimension. In other words, a one dimensional array has a dimension of one. A two-dimensional array has a dimension of 2, and so on.

To find out the dimension of an array, the Array class provides the Rank property. Therefore, to know the dimension of an existing array, you can access its Rank property.

Fundamental Operations on an Array

Adding a Value to an Array

We know that, to initialize an array, you can open the curly brackets and list its members separated by commas, or you could access each member and assign it the desired value. To support the ability to add members to an array, the Array class is equipped with a method named SetValue that comes in different versions. To add a new item to the types of arrays we have used so far, you can call the following version of the Array.SetValue() method:

public void SetValue(object value, int index);

The first argument is the value to add to the list. The second argument is the index of the member to be added. The first item has index 1; the second item has index 2, and so on. If the array is a list of primitive values, simply pass the value for the first argument. Here are examples of calling the method:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        Array numbers = Array.CreateInstance(typeof(double), 5);

	    numbers.SetValue(7628.937, 0);
		numbers.SetValue(6.48, 1);
		numbers.SetValue(574.9, 2);
	    numbers.SetValue(293749.064, 3);
    	numbers.SetValue(0.70257, 4);

        return 10000;
    }
}

If the array is a list of objects, use any technique to create an object and pass it as the first argument. Here are examples:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        Array elements = Array.CreateInstance(typeof(Element), 5);

	    Element K = new Element();
    	K.Symbol = "K";
	    K.AtomicNumber = 19;
    	K.ElementName = "Potassium";
	    K.AtomicWeight = 39.098f;

    	Element Ca = new Element(20);
	    Element Sc = new Element("Sc");
    	Element Ti = new Element(22, "Ti", "Titanium", 47.867F);

	    elements.SetValue(K, 0);
    	elements.SetValue(Ca, 1);
	    elements.SetValue(Sc, 2);
    	elements.SetValue(Ti, 3);
	    elements.SetValue(new Element(23), 4);
    	elements.SetValue(new Element(24, "Cr", "Chromium", 51.996F), 5);

        return 1_000;
    }
}

We indicated that whenever you create an array, you are in fact declaring an instance of the Array class. Therefore, even if you create an array using the square bracket formula, you can still call the SetValue() method to specify any member of the array. Here is an example:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        var numbers = new double[5];

	    numbers.SetValue(7628.937, 0);
    	numbers.SetValue(6.48, 1);
	    numbers.SetValue(574.9, 2);
    	numbers.SetValue(293749.064, 3);
	    numbers.SetValue(0.70257, 4);

        return 10_000;
    }
}

The Array class provides a SetValue() version for each corresponding CreateInstance() method we reviewed earlier.

Practical LearningPractical Learning: Adding Objects to an Array

Getting a Value from an Array

To support the ability to retrieve the value of a member of an array, the Array class is equipped with a method named GetValue that is overloaded with a version corresponding to each version of the CreateInstance() and the SetValue() methods. For example, to access the values stored in a one-dimensional array, you can call this version:

public object GetValue(int index);

The index argument is the zero-based index of the member whose value you want to access. If the array is a list of primitive values, the Array.GetValue() method directly produces the value stored in the indicated position. Here is an example:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        var numbers = new double[5];

        numbers.SetValue(7628.937, 0);
        numbers.SetValue(6.48, 1);
        numbers.SetValue(574.9, 2);
        numbers.SetValue(293749.064, 3);
        numbers.SetValue(0.70257, 4);

        WriteLine("Number: {0}", numbers.GetValue(0));
        WriteLine("=================================");
        return 0;
    }
}

This would produce:

Number: 7628.937
=================================
Press any key to continue . . .

Notice that the Array.GetValue() method returns an anonymous object. This means that it can return anything. Therefore, if the array you are using is a list of objects, you must cast the returned object to the appropriate class. When calling the Array.GetValue() method, if you pass an invalid value, the application would throw an exception.

Practical LearningPractical Learning: Getting the Objects of an Arrray

Looping for an Array

To access one member of the array at a time, you can use a loop to access any member using its index. You can use any of the classic three loops: for, while, or do...while. Here is an example that uses a for loop and the Length property to know the number of members of an array:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        const int length = 5;

        var numbers = new double[length];

        numbers.SetValue(7628.937, 0);
        numbers.SetValue(6.48, 1);
        numbers.SetValue(574.9, 2);
        numbers.SetValue(293749.064, 3);
        numbers.SetValue(0.70257, 4);
        
        for(int i = 0; i < numbers.Length; i++)
           WriteLine("Number: {0}", numbers.GetValue(i));

        WriteLine("=================================");
        return 20;
    }
}

This would produce:

Number: 7628.937
Number: 6.48
Number: 574.9
Number: 293749.064
Number: 0.70257
=================================
Press any key to continue . . .

Practical LearningPractical Learning: Looping Through an Arrray of Objects

  1. To display the list of states, type the following code:
    using System;
    using System.Windows.Forms;
    
    namespace CountriesStatistics6
    {
        public partial class Form1 : Form
        {
            public Array States;
            public Array Regions;
    
            public Form1()
            {
                InitializeComponent();
    
                Regions = Array.CreateInstance(typeof(Region), 9);
                States  = Array.CreateInstance(typeof(Federation), 30);
    
                Regions.SetValue(new Region() { Designation = "East North Central", Description = "The East North Central region includes the states around the Great Lakes." }, 0);
                Regions.SetValue(new Region() { Designation = "East South Central", Description = "The East South Central portion is one of the regions designated as the South." }, 1);
                Regions.SetValue(new Region() { Designation = "New England",        Description = "New England is the group of states in the North-East region. It is delimited in the North and North-East by Canada, in the East by the Atlantic Ocean, and in the South and West by the New York state." }, 2);
                Regions.SetValue(new Region() { Designation = "Mid-Atlantic",       Description = "Mid-Atlantic is a region situated in the south of New England. Mid-Atlantic is one of the regions defined by the Census bureau for statistical purposes." }, 3);
                Regions.SetValue(new Region() { Designation = "Mountain",           Description = "Like the name suggests, the Mountain region covers states known for their mountaneous characteristics. They are also covered by desertic areas." }, 4);
                Regions.SetValue(new Region() { Designation = "Pacific",            Description = "The Pacific region covers the costal western states plus the two non-continental states of Alaska and the Hawaiian islands. All states in this region have a coast on the Pacific Ocean." }, 5);
                Regions.SetValue(new Region() { Designation = "South Atlantic",     Description = "The South Atlantic region includes the states in the South-East part but also counts the Disctrict of Columbia." }, 6);
                Regions.SetValue(new Region() { Designation = "West North Central", Description = "The West North Central region includes the states in the Great Planes area. This reqion is divided from the East North Central part by the Mississippi River. This region is characterized by vast agricultural farms and high employment." }, 7);
                Regions.SetValue(new Region() { Designation = "West South Central", Description = "The West South Central part is one of the regions with (only) four states. The imposing Texas state is both the largest and the most populous state in the region." }, 8);
    
                States.SetValue(new Federation() { Abbreviation = "RI", Name = "Rhode Island",   Area =   1545, AreaSqrKms =    4002, AdmissionUnionOrder = 13, Capital = "Providence",     Region = (Region)(Regions.GetValue(2)) },  0);
                States.SetValue(new Federation() { Abbreviation = "OH", Name = "Ohio",           Area =  44828, AreaSqrKms =  116103, AdmissionUnionOrder = 17, Capital = "Columbus",       Region = (Region)(Regions.GetValue(0)) },  1);
                States.SetValue(new Federation() { Abbreviation = "KY", Name = "Kentucky",       Area =  40411, AreaSqrKms =  104665, AdmissionUnionOrder = 15, Capital = "Frankfort",      Region = (Region)(Regions.GetValue(1)) },  2);
                States.SetValue(new Federation() { Abbreviation = "IA", Name = "Iowa",           Area =  56276, AreaSqrKms =  145754, AdmissionUnionOrder = 29, Capital = "Des Moines",     Region = (Region)(Regions.GetValue(7)) },  3);
                States.SetValue(new Federation() { Abbreviation = "WI", Name = "Wisconsin",      Area =  65503, AreaSqrKms =  169653, AdmissionUnionOrder = 30, Capital = "Madison",        Region = (Region)(Regions.GetValue(0)) },  4);
                States.SetValue(new Federation() { Abbreviation = "VT", Name = "Vermont",        Area =   9615, AreaSqrKms =   24903, AdmissionUnionOrder = 14, Capital = "Montpelier",     Region = (Region)(Regions.GetValue(2)) },  5);
                States.SetValue(new Federation() { Abbreviation = "ID", Name = "Idaho",          Area =  83574, AreaSqrKms =  216456, AdmissionUnionOrder = 43, Capital = "Boise",          Region = (Region)(Regions.GetValue(4)) },  6);
                States.SetValue(new Federation() { Abbreviation = "ME", Name = "Maine",          Area =  35387, AreaSqrKms =   91653, AdmissionUnionOrder = 23, Capital = "Augusta",        Region = (Region)(Regions.GetValue(2)) },  7);
                States.SetValue(new Federation() { Abbreviation = "OR", Name = "Oregon",         Area =  98386, AreaSqrKms =  254819, AdmissionUnionOrder = 33, Capital = "Salem",          Region = (Region)(Regions.GetValue(5)) },  8);
                States.SetValue(new Federation() { Abbreviation = "ND", Name = "North Dakota",   Area =  70704, AreaSqrKms =  183123, AdmissionUnionOrder = 39, Capital = "Bismarck",       Region = (Region)(Regions.GetValue(7)) },  9);
                States.SetValue(new Federation() { Abbreviation = "IN", Name = "Indiana",        Area =  36420, AreaSqrKms =   94328, AdmissionUnionOrder = 19, Capital = "Indianapolis",   Region = (Region)(Regions.GetValue(0)) }, 10);
                States.SetValue(new Federation() { Abbreviation = "MS", Name = "Mississippi",    Area =  48434, AreaSqrKms =  125443, AdmissionUnionOrder = 20, Capital = "Jackson",        Region = (Region)(Regions.GetValue(1)) }, 11);
                States.SetValue(new Federation() { Abbreviation = "TX", Name = "Texas",          Area = 268601, AreaSqrKms =  695676, AdmissionUnionOrder = 28, Capital = "Austin",         Region = (Region)(Regions.GetValue(8)) }, 12);
                States.SetValue(new Federation() { Abbreviation = "MT", Name = "Montana",        Area = 147046, AreaSqrKms =  380850, AdmissionUnionOrder = 41, Capital = "Helena",         Region = (Region)(Regions.GetValue(4)) }, 13);
                States.SetValue(new Federation() { Abbreviation = "NC", Name = "North Carolina", Area =  53821, AreaSqrKms =  139397, AdmissionUnionOrder = 12, Capital = "Raleigh",        Region = (Region)(Regions.GetValue(6)) }, 14);
                States.SetValue(new Federation() { Abbreviation = "TN", Name = "Tennessee",      Area =  42146, AreaSqrKms =  109158, AdmissionUnionOrder = 16, Capital = "Nashville",      Region = (Region)(Regions.GetValue(1)) }, 15);
                States.SetValue(new Federation() { Abbreviation = "NE", Name = "Nebraska",       Area =  77358, AreaSqrKms =  200358, AdmissionUnionOrder = 37, Capital = "Lincoln",        Region = (Region)(Regions.GetValue(7)) }, 16);
                States.SetValue(new Federation() { Abbreviation = "IL", Name = "Illinois",       Area =  57918, AreaSqrKms =  150007, AdmissionUnionOrder = 21, Capital = "Springfield",    Region = (Region)(Regions.GetValue(0)) }, 17);
                States.SetValue(new Federation() { Abbreviation = "KS", Name = "Kansas",         Area =  82282, AreaSqrKms =  213110, AdmissionUnionOrder = 34, Capital = "Topeka",         Region = (Region)(Regions.GetValue(7)) }, 18);
                States.SetValue(new Federation() { Abbreviation = "NH", Name = "New Hampshire",  Area =   9351, AreaSqrKms =   24219, AdmissionUnionOrder =  9, Capital = "Concord",        Region = (Region)(Regions.GetValue(2)) }, 19);
                States.SetValue(new Federation() { Abbreviation = "DE", Name = "Delaware",       Area =   2489, AreaSqrKms =    6447, AdmissionUnionOrder =  1, Capital = "Dover",          Region = (Region)(Regions.GetValue(6)) }, 20);
                States.SetValue(new Federation() { Abbreviation = "NJ", Name = "New Jersey",     Area =   8722, AreaSqrKms =   22590, AdmissionUnionOrder =  3, Capital = "Trenton",        Region = (Region)(Regions.GetValue(3)) }, 21);
                States.SetValue(new Federation() { Abbreviation = "AK", Name = "Alaska",         Area = 656424, AreaSqrKms = 1700139, AdmissionUnionOrder = 49, Capital = "Juneau",         Region = (Region)(Regions.GetValue(5)) }, 22);
                States.SetValue(new Federation() { Abbreviation = "NM", Name = "New Mexico",     Area = 121598, AreaSqrKms =  314939, AdmissionUnionOrder = 47, Capital = "Santa Fe",       Region = (Region)(Regions.GetValue(4)) }, 23);
                States.SetValue(new Federation() { Abbreviation = "NY", Name = "New York",       Area =  54475, AreaSqrKms =  141089, AdmissionUnionOrder = 11, Capital = "Albany",         Region = (Region)(Regions.GetValue(3)) }, 24);
                States.SetValue(new Federation() { Abbreviation = "CA", Name = "California",     Area = 163707, AreaSqrKms =  424002, AdmissionUnionOrder = 31, Capital = "Sacramento",     Region = (Region)(Regions.GetValue(5)) }, 25);
                States.SetValue(new Federation() { Abbreviation = "MO", Name = "Missouri",       Area =  69709, AreaSqrKms =  180546, AdmissionUnionOrder = 24, Capital = "Jefferson City", Region = (Region)(Regions.GetValue(7)) }, 26);
                States.SetValue(new Federation() { Abbreviation = "OK", Name = "Oklahoma",       Area =  69903, AreaSqrKms =  181049, AdmissionUnionOrder = 46, Capital = "Oklahoma City",  Region = (Region)(Regions.GetValue(8)) }, 27);
                States.SetValue(new Federation() { Abbreviation = "PA", Name = "Pennsylvania",   Area =  46058, AreaSqrKms =  119291, AdmissionUnionOrder =  2, Capital = "Harrisburg",     Region = (Region)(Regions.GetValue(3)) }, 28);
                States.SetValue(new Federation() { Abbreviation = "SC", Name = "South Carolina", Area =  32007, AreaSqrKms =   82898, AdmissionUnionOrder =  8, Capital = "Columbia",       Region = (Region)(Regions.GetValue(6)) }, 29);
    
                ListViewItem lviState = null;
    
                for(int counter = 0; counter <= States.Length - 1; counter++)
                {
                    Federation stt = (Federation)States.GetValue(counter);
    
                    lviState = new ListViewItem((counter + 1).ToString());
    
                    lviState.SubItems.Add(stt.Abbreviation);
                    lviState.SubItems.Add(stt.StateName);
                    lviState.SubItems.Add(stt.AreaSqrMiles.ToString());
                    lviState.SubItems.Add(stt.AreaSqrKms.ToString());
                    lviState.SubItems.Add(stt.AdmissionUnionOrder.ToString());
                    lviState.SubItems.Add(stt.Capital);
                    lviState.SubItems.Add(stt.Region.Designation);
    
                    lvwStates.Items.Add(lviState);
                }
            }
        }
    }
  2. To execute, on the main menu, click Debug -> Start Without Debugging:

    Looping Through an Arrray of Objects

  3. Close the form and return to your programming environment
  4. Close your programming environment

Previous Copyright © 2008-2021, FunctionX Next