A List as an Array of Values

Introduction

A database is a list of values. The values can be organized to make it easy to retrieve and optionally manipulate them. A computer database is a list of values that are stored in the computer, usually as one or more files. The values can then be accessed when needed. Probably the most fundamental type of list of values can be created, and managed, as an array.

Practical LearningPractical Learning: Introducing Collections Applications

  1. Start Microsoft Visual Studio 2022

    Create New Project

  2. In the Visual Studio 2022 dialog box, click Create a New Project
  3. In the Create a New Project wizard page, in the languages combo box, select C#

    Create New Project

  4. In the list of the projects templates, click Windows Forms App
  5. Click Next
  6. In the Configure Your New Project dialog box, change the project Name to IntroductionToCollections
    Accept or change the project Location
  7. Click Next
  8. In the Framework combo box, select the highest version: .NET 8.0 (Long-Term Support)
  9. Click Create
  10. Double-click an unoccupied area of the form to generate its Load event
  11. To execute, on the main menu, click Debug -> Start Without Debugging
  12. Close the form and return to your programming environment
Author Note

Author Note

If you want, using the form of the application you created, you can apply the descriptions in the following sections to experiment with, and get, the same results.

Creating an Array

Before creating an array, you must decide what type of values each element of the array would be. A simple array can be made of primitive types of values. Here is an example:

namespace Arrays
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }
 
        private void Exercise_Load(object sender, EventArgs e)
        {
            var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
        }
    }
}

Once the array has been created, you can access each one of its elements using the [] operator. Here is an example:

private void Exercise_Load(object sender, EventArgs e)
{
    var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
 
    for (int i = 0; i < 5; i++)
        lbxNumbers.Items.Add(numbers[i].ToString());
}

Array

An array can also be made of elements that are each a composite type. That is, each element can be of a class type. Of course, you must have a class first. You can use one of the many built-in classes of the .NET Framework or you can create your own class. Here is an example:

namespace Arrays
{
    public enum Genders { Male, Female, Unknown };
 
    public class Person
    {
        public int PersonID;
        public string FirstName;
        public string LastName;
        public Genders Gender;
    }
}

After creating the class, you can then use it as the type of the array. Here is an example:

namespace Arrays
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }
 
        private void Exercise_Load(object sender, EventArgs e)
        {
            var people = new Person[]
            {
                new Person()
                {
                    PersonID = 72947, Gender = Genders.Female,
                    FirstName = "Paulette", LastName = "Cranston"
                },
            
                new Person()
                {
                    PersonID = 70854, Gender = Genders.Male,
                    FirstName = "Harry", LastName = "Kumar"
                },
            
                new Person()
                {
                    PersonID = 27947, Gender = Genders.Male,
                    FirstName = "Jules", LastName = "Davidson"
                },
                
                new Person()
                {
                    PersonID = 62835, Gender = Genders.Unknown,
                    FirstName = "Leslie", LastName = "Harrington"
                },
            
                new Person()
                {
                    PersonID = 92958, Gender = Genders.Male,
                    FirstName = "Ernest", LastName = "Colson"
                },
                
                new Person()
                {
                    PersonID = 91749, Gender = Genders.Female,
                    FirstName = "Patricia", LastName = "Katts"
                },
            
                new Person()
                {
                    PersonID = 29749, Gender = Genders.Unknown,
                    FirstName = "Patrice", LastName = "Abanda"
                },
            
                new Person()
                {
                    PersonID = 24739, Gender = Genders.Male,
                    FirstName = "Frank", LastName = "Thomasson"
                }
            };
 
            for (int i = 0; i < 8; i++)
            {
                ListViewItem lviPerson = new ListViewItem(people[i].FirstName);
 
                lviPerson.SubItems.Add(people[i].LastName);
                lviPerson.SubItems.Add(people[i].Gender.ToString());
 
                lvwPeople.Items.Add(lviPerson);
            }
        }
    }
}

Array

Introduction to the Array Class

To assist you with creating or managing arrays, the .NET Framework provides the Array class. Every array you create is derived from this class. As a result, all arrays of your program share many characteristics and they get their foundation from the Array class, which include its properties and methods. Once you declare an array variable, it automatically has access to the members of the Array class. For example, instead of counting the number of elements in an array, you can access the Length property of the array variable. Here is an example:

private void Exercise_Load(object sender, EventArgs e)
{
    int[] Numbers = new int[] { 20, 5, 83405, 734, 5 };
 
    for (int i = 0; i < Numbers.Length; i++)
        lbxNumbers.Items.Add(numbers[i].ToString());
}

In traditional languages, when you declare an array variable, you must specify the number of elements that the array will contain. You must do this especially if you declare the variable without initializing the array. Here is an example:

namespace Arrays
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }
 
        private void Exercise_Load(object sender, EventArgs e)
        {
            var people = new Person[4];
        }
    }
}

After declaring the variable, before using the array, you must initialize it. Otherwise you would receive an error. When initializing the array, you can only initialize it with the number of elements you had specified. To illustrate this, consider the following program:

namespace Arrays
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }
 
        private void Exercise_Load(object sender, EventArgs e)
        {
            var people = new Person[4];
 
            people[0] = new Person()
            {
                PersonID = 72947, FirstName = "Paulette",
                LastName = "Cranston", Gender = Genders.Female
            };
 
            people[1] = new Person()
            {
                PersonID = 70854, FirstName = "Harry",
                LastName = "Kumar", Gender = Genders.Male
            };
 
            people[2] = new Person()
            {
                PersonID = 27947, FirstName = "Jules",
                LastName = "Davidson", Gender = Genders.Male
            };
 
            people[3] = new Person()
            {
                PersonID = 62835, FirstName = "Leslie",
                LastName = "Harrington", Gender = Genders.Unknown
            };
 
            people[4] = new Person()
            {
                PersonID = 92958, FirstName = "Ernest",
                LastName = "Colson", Gender = Genders.Male
            };
 
            people[5] = new Person()
            {
                PersonID = 91749, FirstName = "Patricia",
                LastName = "Katts", Gender = Genders.Female
            };
 
            for (int i = 0; i < People.Length; i++)
            {
                ListViewItem lviPerson = new ListViewItem(people[i].FirstName);
 
                lviPerson.SubItems.Add(people[i].LastName);
                lviPerson.SubItems.Add(people[i].Gender.ToString());
 
                lvwPeople.Items.Add(lviPerson);
            }
        }
    }
}

Notice that the variable is declared to hold only 4 elements but the user tries to access a 5th one. This would produce an IndexOutOfRangeExcception exception:

Index out of Range

Resizing an Array

One of the most valuable features of the Array class is that it allows an array to be "resizable". That is, if you find out that an array has a size smaller than the number of elements you want to add to it, you can increase its capacity. To support this, the Array class is equipped with the static Resize() method. Its syntax is:

public static void Resize<T>(ref T[] array, int newSize);

As you can see, this is a generic method that takes two arguments. The first argument is the name of the array variable that you want to resize. It must be passed by reference. The second argument is the new size you want the array to have. Here is an example of calling this method:

private void Exercise_Load(object sender, EventArgs e)
{
    var people = new Person[4];
 
    people[0] = new Person()
    {
        PersonID = 72947, FirstName = "Paulette",
        LastName = "Cranston", Gender = Genders.Female
    };
 
    people[1] = new Person()
    {
        PersonID = 70854, FirstName = "Harry",
        LastName = "Kumar", Gender = Genders.Male
    };
 
    people[2] = new Person()
    {
        PersonID = 27947, FirstName = "Jules",
        LastName = "Davidson", Gender = Genders.Male
    };
 
    people[3] = new Person()
    {
        PersonID = 62835, FirstName = "Leslie",
        LastName = "Harrington", Gender = Genders.Unknown
    };
 
    Array.Resize<Person>(ref People, 6);
 
    people[4] = new Person()
    {
        PersonID = 92958, FirstName = "Ernest",
        LastName = "Colson", Gender = Genders.Male
    };
 
    people[5] = new Person()
    {
        PersonID = 91749, FirstName = "Patricia",
        LastName = "Katts", Gender = Genders.Female
    };
 
    for (int i = 0; i < People.Length; i++)
    {
        ListViewItem lviPerson = new ListViewItem(people[i].FirstName);
 
        lviPerson.SubItems.Add(people[i].LastName);
        lviPerson.SubItems.Add(people[i].Gender.ToString());
 
        lvwPeople.Items.Add(lviPerson);
    }
}

The advantage of this approach is that you can access the array from any member of the same class or even from another file of the same program.

An Array as a Field

As done previously, you can create an array in a method. A disadvantage of this approach is that the array can be accessed from only the method (or event) in which it is created. As an alternative, you can declare an array as a member of a class. Here is an example:

namespace Arrays
{
    public partial class Exercise : Form
    {
        Person[] People;
 
        public Exercise()
        {
            InitializeComponent();
        }
    }
}

The advantage of this approach is that you can access the array from any member of the same class or even from another file of the same program. After declaring the variable, you can initialize it. You can do this in a constructor or in an event that would be fired before any other event that would use the array. This type of initialization is usually done in a Load event of a form. After initializing the array, you can then access in another method or another event of the form. Here is an example:

namespace Arrays
{
    public partial class Exercise : Form
    {
        Person[] People;
 
        public Exercise()
        {
            InitializeComponent();
        }
 
        private void Exercise_Load(object sender, EventArgs e)
        {
            People = new Person[]
            {
                new Person()
                {
                    PersonID = 72947, Gender = Genders.Female,
                    FirstName = "Paulette", LastName = "Cranston"
                },
            
                new Person()
                {
                    PersonID = 70854, Gender = Genders.Male,
                    FirstName = "Harry", LastName = "Kumar"
                },
            
                new Person()
                {
                    PersonID = 27947, Gender = Genders.Male,
                    FirstName = "Jules", LastName = "Davidson"
                },
                
                new Person()
                {
                    PersonID = 62835, Gender = Genders.Unknown,
                    FirstName = "Leslie", LastName = "Harrington"
                },
            
                new Person()
                {
                    PersonID = 92958, Gender = Genders.Male,
                    FirstName = "Ernest", LastName = "Colson"
                },
                
                new Person()
                {
                    PersonID = 91749, Gender = Genders.Female,
                    FirstName = "Patricia", LastName = "Katts"
                },
            
                new Person()
                {
                    PersonID = 29749, Gender = Genders.Unknown,
                    FirstName = "Patrice", LastName = "Abanda"
                },
            
                new Person()
                {
                    PersonID = 24739, Gender = Genders.Male,
                    FirstName = "Frank", LastName = "Thomasson"
                }
            };
 
            foreach (Person pers in People)
            {
                ListViewItem lviPerson = new ListViewItem(pers.PersonID.ToString());
 
                lviPerson.SubItems.Add(pers.FirstName);
                lviPerson.SubItems.Add(pers.LastName);
                lviPerson.SubItems.Add(pers.Gender.ToString());
 
                lvwPeople.Items.Add(lviPerson);
            }
        }
    }
}

Arrays and methods

Passing an Array as Argument

An array can be passed as argument to a method. Here s an example:

namespace Arrays
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }
 
        private void ArrayInitializer(Person[] People)
        {
        }
    }
}

In the method, you can use the array as you see fit. For example you can assign values to the elements of the array. When calling a method that is passed an array, you can pass the argument by reference so it would come back with new values. Here are examples:

namespace Arrays
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }
 
        private void ArrayInitializer(ref Person[] People)
        {
            People = new Person[]
            {
                new Person()
                {
                    PersonID = 72947, Gender = Genders.Female,
                    FirstName = "Paulette", LastName = "Cranston"
                },
            
                new Person()
                {
                    PersonID = 7085, Gender = Genders.Male4,
                    FirstName = "Harry", LastName = "Kumar"
                },
            
                new Person()
                {
                    PersonID = 27947, Gender = Genders.Male,
                    FirstName = "Jules", LastName = "Davidson"
                },
                
                new Person()
                {
                    PersonID = 62835, Gender = Genders.Unknown,
                    FirstName = "Leslie", LastName = "Harrington"
                },
            
                new Person()
                {
                    PersonID = 92958, Gender = Genders.Male,
                    FirstName = "Ernest", LastName = "Colson"
                },
                
                new Person()
                {
                    PersonID = 91749, Gender = Genders.Female,
                    FirstName = "Patricia", LastName = "Katts"
                },
            
                new Person()
                {
                    PersonID = 29749, Gender = Genders.Unknown,
                    FirstName = "Patrice", LastName = "Abanda"
                },
            
                new Person()
                {
                    PersonID = 24739, Gender = Genders.Male,
                    FirstName = "Frank", LastName = "Thomasson"
                }
            };
        }
 
        private void ShowPeople(Person[] People)
        {
            foreach (Person pers in People)
            {
                ListViewItem lviPerson = new ListViewItem(pers.PersonID.ToString());
 
                lviPerson.SubItems.Add(pers.FirstName);
                lviPerson.SubItems.Add(pers.LastName);
                lviPerson.SubItems.Add(pers.Gender.ToString());
 
                lvwPeople.Items.Add(lviPerson);
            }
        }
 
 
        private void Exercise_Load(object sender, EventArgs e)
        {
            Person[] persons = new Person[8];
 
            ArrayInitializer(ref persons);
            ShowPeople(persons);
        }
    }
}

Returning an Array

A method can be created to return an array. When creating the method, on the left side of the name of the method, type the name of the type of value the method would return, including the square brackets. In the method, create and initialize an array. Before exiting the method, you must return the array. Here is an example:

namespace Arrays
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }
 
        private Person[] ArrayInitializer()
        {
            Person[] People = new Person[]
            {
                new Person()
                {
                    PersonID = 72947, Gender = Genders.Female,
                    FirstName = "Paulette", LastName = "Cranston"
                },
            
                new Person()
                {
                    PersonID = 70854, Gender = Genders.Male,
                    FirstName = "Harry", LastName = "Kumar"
                },
            
                new Person()
                {
                    PersonID = 27947, Gender = Genders.Male,
                    FirstName = "Jules", LastName = "Davidson"
                },
                
                new Person()
                {
                    PersonID = 62835, Gender = Genders.Unknown,
                    FirstName = "Leslie", LastName = "Harrington"
                },
            
                new Person()
                {
                    PersonID = 92958, Gender = Genders.Male,
                    FirstName = "Ernest", LastName = "Colson"
                },
                
                new Person()
                {
                    PersonID = 91749, Gender = Genders.Female,
                    FirstName = "Patricia", LastName = "Katts"
                },
            
                new Person()
                {
                    PersonID = 29749, Gender = Genders.Unknown,
                    FirstName = "Patrice", LastName = "Abanda"
                },
            
                new Person()
                {
                    PersonID = 24739, Gender = Genders.Male,
                    FirstName = "Frank", LastName = "Thomasson"
                }
            };
 
            return People;
        }
 
        private void ShowPeople(Person[] People)
        {
            foreach (Person pers in People)
            {
                ListViewItem lviPerson = new ListViewItem(pers.PersonID.ToString());
 
                lviPerson.SubItems.Add(pers.FirstName);
                lviPerson.SubItems.Add(pers.LastName);
                lviPerson.SubItems.Add(pers.Gender.ToString());
 
                lvwPeople.Items.Add(lviPerson);
            }
        }
 
 
        private void Exercise_Load(object sender, EventArgs e)
        {
            Person[] persons = ArrayInitializer();
            ShowPeople(persons);
        }
    }
}

Operations on an Array

Introduction

Because an array is primarily a series of objects or values, there are various pieces of information you would get interested to get from it. Typical operations include:

Although you can write your own routines to perform these operations, the Array class provides most of the methods you would need to get the necessary information.

Adding an Element to an Array

We have seen that, using the [] operator, you can add a new element to an array. Still, to support this operation, the Array class is equipped with the SetValue() method that is overloaded with various versions. Here is an example that adds an element to the third position of the array:

namespace Arrays
{
    public partial class Exercise : Form
    {
        Person[] People;
 
        public Exercise()
        {
            InitializeComponent();
        }
 
        private Person[] ArrayInitializer()
        {
            People = new Person[8];
 
            for(int i = 0; i < 8; i++)
            {
                people[i] = new Person();
                people[i].PersonID = 0;
                people[i].FirstName = "";
                people[i].LastName = "";
                people[i].Gender = Genders.Unknown;
            }
 
            return People;
        }
 
        private void ShowPeople(Person[] People)
        {
            lvwPeople.Items.Clear();
 
            foreach (Person pers in People)
            {
                ListViewItem lviPerson = new ListViewItem(pers.PersonID.ToString());
 
                lviPerson.SubItems.Add(pers.FirstName);
                lviPerson.SubItems.Add(pers.LastName);
                lviPerson.SubItems.Add(pers.Gender.ToString());
 
                lvwPeople.Items.Add(lviPerson);
            }
        }
 
        private void Exercise_Load(object sender, EventArgs e)
        {
            Person[] persons = ArrayInitializer();
            ShowPeople(persons);
        }
 
        private void btnAdd_Click(object sender, EventArgs e)
        {
            Person pers = new Person();
 
            pers.PersonID = int.Parse(txtPersonID.Text);
            pers.FirstName = txtFirstName.Text;
            pers.LastName = txtLastName.Text;
            if (cbxGenders.Text == "Male")
                pers.Gender = Genders.Male;
            else if (cbxGenders.Text == "Female")
                pers.Gender = Genders.Female;
            else
                pers.Gender = Genders.Unknown;
 
            People.SetValue(pers, 2);
            ShowPeople(People);
        }
    }
}

When the Array.SetValue() method is called, it replaces the element at the indicated position.

Getting an Element From an Array

The reverse of adding an item to an array is to retrieve one. You can do this with the [] operator. To support this operation, the Array class is equipped with the GetValue() method that comes in various versions. Here is an example of calling it:

private void lvwPeople_ItemSelectionChanged(object sender,
		ListViewItemSelectionChangedEventArgs e)
{
    Person pers = (Person)People.GetValue(e.ItemIndex);
 
    txtPersonID.Text = pers.PersonID.ToString();
    txtFirstName.Text = pers.FirstName;
    txtLastName.Text = pers.LastName;
    cbxGenders.Text = pers.Gender.ToString();
}

When calling this method, make sure you provide a valid index, if you do not, you would get an IndexOutOfRangeException exception.

Checking the Existence of an Element

Once some elements have been added to an array, you can try to locate one. One of the most fundamental means of looking for an item consists of finding out whether a certain element exists in the array. To support this operation, the Array class is equipped with the Exists() method whose syntax is:

public static bool Exists<T>(T[] array, Predicate<T> match);

This is a generic method that takes two arguments. The first is the array on which you will look for the item. The second argument is a delegate that specifies the criterion to apply. Here is an example:

namespace Arrays
{
    public partial class Exercise : Form
    {
        Person[] People;
        static int IDToFind;
 
        public Exercise()
        {
            InitializeComponent();
        }
 
        private Person[] ArrayInitializer()
        {
            People = new Person[]
            {
                . . . No Change
            };
 
            return People;
        }
 
        private void ShowPeople(Person[] People)
        {
            lvwPeople.Items.Clear();
 
            foreach (Person pers in People)
            {
                ListViewItem lviPerson = new ListViewItem(pers.PersonID.ToString());
 
                lviPerson.SubItems.Add(pers.FirstName);
                lviPerson.SubItems.Add(pers.LastName);
                lviPerson.SubItems.Add(pers.Gender.ToString());
 
                lvwPeople.Items.Add(lviPerson);
            }
        }
 
        private void Exercise_Load(object sender, EventArgs e)
        {
            Person[] persons = ArrayInitializer();
            ShowPeople(persons);
        }
 
        private void btnAdd_Click(object sender, EventArgs e)
        {
            Person pers = new Person();
 
            pers.PersonID = int.Parse(txtPersonID.Text);
            pers.FirstName = txtFirstName.Text;
            pers.LastName = txtLastName.Text;
            if (cbxGenders.Text == "Male")
                pers.Gender = Genders.Male;
            else if (cbxGenders.Text == "Female")
                pers.Gender = Genders.Female;
            else
                pers.Gender = Genders.Unknown;
 
            People.SetValue(pers, 2);
            ShowPeople(People);
        }
 
        private static bool IDExists(Person p)
        {
            if (p.PersonID == Exercise.IDToFind)
                return true;
            else
                return false;
        }
 
        private void btnExists_Click(object sender, EventArgs e)
        {
            IDToFind = int.Parse(txtPersonID.Text);
 
            if (Array.Exists<Person>(People, IDExists))
                MessageBox.Show("The person was found");
            else
                MessageBox.Show("The person was not found anywhere");
        }
    }
}

Finding an Element

One of the most valuable operations you can perform on an array consists of looking for a particular element. To assist you with this, the Array class is equipped with the Find() method. Its syntax is:

public static T Find<T>(T[] array, Predicate<T> match);

This generic method takes two arguments. The first argument is the name of the array that holds the elements. The second argument is a delegate that has the criterion to be used to find the element. Here is an example:

private void btnFind_Click(object sender, EventArgs e)
{
    IDToFind = int.Parse(txtPersonID.Text);
 
    Person pers = Array.Find<Person>(People, IDExists);
 
    if (pers != null)
    {
        txtFirstName.Text = pers.FirstName;
        txtLastName.Text = pers.LastName;
        cbxGenders.Text = pers.Gender.ToString();
    }
}

Indexers

Introduction

An indexer, also called an indexed property, is a class's property that allows you to access a member variable of a class using the features of an array. To create an indexed property, start the class like any other. In the body of the class, create a field that is an array. The array can be of a primitive type or composite. Obviously if you want to use a composite type, you can use one of the many built-in .NET Framework classes or you must first create your class. Here is an example:

namespace Indexer
{
    public enum Genders { Male, Female, Unknown };
 
    public class Person
    {
        public int PersonID;
        public string FirstName;
        public string LastName;
        public Genders Gender;
    }
}

As stated already, to start creating an indexer, declare an array as a field. Here is an example:

namespace Indexer
{
    public class Persons
    {
        Person[] individual = new Person[5];
    }
}

In the body of the class, create a property named this with its accessor(s). The this property must be the same type as the field it will refer to. The property must take a parameter as an array. This means that it must have square brackets. Inside of the brackets, include the parameter you will use as index to access the members of the array.

You usually access the members of an array using an integer-based index. Therefore, you can use an int type as the index of the array. Of course, the index' parameter must have a name, such as i. This would be done as follows:

namespace Indexer
{
    public class Persons
    {
        Person[] individual = new Person[5];
 
        public Person this[int i]
        {
        }
    }
}

If you want the property to be read-only, include only aget accessor. In the get accessor, you should return an element of the array field the property refers to, using the parameter of the property. This would be done as follows:

namespace Indexer
{
    public class Persons
    {
        Person[] individual = new Person[5];
 
        public Person this[int i]
        {
            get { return individual[i]; }
        }
    }
}

If you want to create an indexer that can only receive values, add it a set accessor only. Here is an example:

namespace Indexer
{
    public class Persons
    {
        Person[] individual = new Person[5];
 
        public Person this[int i]
        {
            set { individual[i] = value; }
        }
    }
}

If you want to create an indexed property that can both receive values and provide values, that is, if you want to create a read/write indexed property, create both a get and a set accessors. Here is an example:

namespace Indexer
{
    public class Persons
    {
        Person[] individual = new Person[5];
 
        public Person this[int i]
        {
            get { return individual[i]; }
            set { individual[i] = value; }
        }
    }
}

After creating a read/write indexer, you can assign its values outside of the class. In other words, clients of the class can change the values to its elements. Remember that the advantage of an indexed property is that each element of the arrayed field can be accessed from the instance of the class by directly applying the square brackets and the (appropriate) index to it. Here is an example:

namespace Indexer
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }
 
        private void Exercise_Load(object sender, EventArgs e)
        {
            Persons People = new Persons();
 
            people[0] = new Person()
            {
                PersonID = 72947, Gender = Genders.Female,
                FirstName = "Paulette", LastName = "Cranston"
            };
            
            people[1] = new Person()
            {
                PersonID = 70854, Gender = Genders.Male,
                FirstName = "Harry", LastName = "Kumar"
            };
            
            people[2] = new Person()
            {
                PersonID = 27947, Gender = Genders.Male,
                FirstName = "Jules", LastName = "Davidson"
            };
            
            people[3] = new Person()
            {
                PersonID = 62835, Gender = Genders.Unknown,
                FirstName = "Leslie", LastName = "Harrington"
            };
            
            people[4] = new Person()
            {
                PersonID = 92958, FirstName = "Ernest",
                LastName = "Colson", Gender = Genders.Male
            };
 
            for (int i = 0; i < 5; i++ )
            {
            ListViewItem lviPerson = new ListViewItem(people[i].PersonID.ToString());
 
                lviPerson.SubItems.Add(people[i].FirstName);
                lviPerson.SubItems.Add(people[i].LastName);
                lviPerson.SubItems.Add(people[i].Gender.ToString());
 
                lvwPeople.Items.Add(lviPerson);
            }
        }
    }
}

This would produce:

Array-Based and Collection-Based Indexers

When using an indexed property whose field is array-based, you can access only up to the number of elements specified when creating the indexer. In our example, that would be 5. If you try accessing more elements than that, you would receive an IndexOutOfRangeException exception. And because, when using the indexed property, it is treated as a normal class and not an array, you cannot call the Array.Resize() method to increase the number of elements that the variable can hold. If you want to go beyond the number of elements primarily specified, you have various alternatives. You can specify a higher number of elements when creating the indexer. Here is an example:

namespace Indexer
{
    public class Persons
    {
        Person[] individual = new Person[100];
 
        public Person this[int i]
        {
            get { return individual[i]; }
            set { individual[i] = value; }
        }
    }
}

The disadvantage to this approach is that every time this program runs, it would use more memory than it needs. Of course this means that it is not a professional technique of solving a problem. An alternative is to create your own means of increasing the number of elements that the variable can hold. Here is an example:

namespace Indexer
{
    public class Persons
    {
        Person[] individual = new Person[5];
 
        public Person this[int i]
        {
            get { return individual[i]; }
            set { individual[i] = value; }
        }
 
        public void Increase()
        {
            Array.Resize<Person>(ref individual, individual.Length + 5);
        }
    }
}

After doing this, whenever you know you are about to access an increased number of elements, you can simply apply your means of increasing the size. Here is an example:

namespace Indexer
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }
 
        private void Exercise_Load(object sender, EventArgs e)
        {
            Persons People = new Persons();
 
            people[0] = new Person()
            {
                PersonID = 72947, Gender = Genders.Female,
                FirstName = "Paulette", LastName = "Cranston"
            };
            
            people[1] = new Person()
            {
                PersonID = 70854, Gender = Genders.Male,
                FirstName = "Harry", LastName = "Kumar"
            };
            
            people[2] = new Person()
            {
                PersonID = 27947, Gender = Genders.Male,
                FirstName = "Jules", LastName = "Davidson"
            };
            
            people[3] = new Person()
            {
                PersonID = 62835, Gender = Genders.Unknown,
                FirstName = "Leslie", LastName = "Harrington"
            };
            
            people[4] = new Person()
            {
                PersonID = 92958, FirstName = "Ernest",
                LastName = "Colson", Gender = Genders.Male
            };
 
            People.Increase();
 
            people[5] = new Person()
            {
                PersonID = 91749, FirstName = "Patricia",
                LastName = "Katts", Gender = Genders.Female
            };
            
            people[6] = new Person()
            {
                PersonID = 29749, FirstName = "Patrice",
                LastName = "Abanda", Gender = Genders.Unknown
            };
            
            people[7] = new Person()
            {
                PersonID = 24739, FirstName = "Frank",
                LastName = "Thomasson", Gender = Genders.Male
            };
 
            for (int i = 0; i < 8; i++ )
            {
                ListViewItem lviPerson = new ListViewItem(people[i].PersonID.ToString());
 
                lviPerson.SubItems.Add(people[i].FirstName);
                lviPerson.SubItems.Add(people[i].LastName);
                lviPerson.SubItems.Add(people[i].Gender.ToString());
 
                lvwPeople.Items.Add(lviPerson);
            }
        }
    }
}

One more alternative to this problem consists of creating the indexer as a collection.

Multi-Parameterized Indexed Properties

Instead of a single parameter, you can create an indexed property that takes more than one parameter. To start, you can declare the array as a field of a class. After declaring the array, create a this property that takes the parameters. In the body of an accessor (get or set), use the parameter as appropriately as you see fit. At a minimum, for a get accessor, you can return the value of the array using the parameters based on the rules of a two-dimensional array. Here is an example for an indexed property that relates to a two-dimensional array:

namespace Indexer
{
    public class Persons
    {
        Person[, ] individual = new Person[2, 4];
 
        public Person this[int i, int j]
        {
            get { return individual[i, j]; }
            set { individual[i, j] = value; }
        }
    }
}

 After creating the property, you can access each element of the array by applying the square brackets to an instance of the class. Here is an example:

namespace Indexer
{
    public partial class Exercise : Form
    {       
        public Exercise()
        {
            InitializeComponent();
        }
 
        private void Exercise_Load(object sender, EventArgs e)
        {
            Persons People = new Persons();
 
            people[0, 0] = new Person()
            {
                PersonID = 72947, Gender = Genders.Female,
                FirstName = "Paulette", LastName = "Cranston"
            };
            
            people[0, 1] = new Person()
            {
                PersonID = 70854, Gender = Genders.Male,
                FirstName = "Harry", LastName = "Kumar"
            };
            
            people[0, 2] = new Person()
            {
                PersonID = 27947, Gender = Genders.Male,
                FirstName = "Jules", LastName = "Davidson"
            };
            
            people[0, 3] = new Person()
            {
                PersonID = 62835, Gender = Genders.Unknown,
                FirstName = "Leslie", LastName = "Harrington"
            };
            
            people[1, 0] = new Person()
            {
                PersonID = 92958, FirstName = "Ernest",
                LastName = "Colson", Gender = Genders.Male
            };
 
            people[1, 1] = new Person()
            {
                PersonID = 91749, FirstName = "Patricia",
                LastName = "Katts", Gender = Genders.Female
            };
            
            people[1, 2] = new Person()
            {
                PersonID = 29749, FirstName = "Patrice",
                LastName = "Abanda", Gender = Genders.Unknown
            };
            
            people[1, 3] = new Person()
            {
                PersonID = 24739, FirstName = "Frank",
                LastName = "Thomasson", Gender = Genders.Male
            };
 
            for (int i = 0; i < 2; i++ )
            {
                for (int j = 0; j < 4; j++)
                {
		    ListViewItem lviPerson = new ListViewItem(people[i, j].PersonID.ToString());
 
                    lviPerson.SubItems.Add(people[i, j].FirstName);
                    lviPerson.SubItems.Add(people[i, j].LastName);
                    lviPerson.SubItems.Add(people[i, j].Gender.ToString());
 
                    lvwPeople.Items.Add(lviPerson);
                }
            }
        }
    }
}

Remember that one of the most valuable features of an indexed property is that, when creating it, you can make it return any primitive type and you can make it take any parameter of your choice. Also, the parameters of a multi-parameter indexed property do not have to be the same type. One can be a character while the other is a bool type; one can be a double while the other is a short, one can be an integer while the other is a string. When defining the property, you must apply the rules of both the methods and the arrays.

Practical LearningPractical Learning: Ending the Lesson


Home Copyright © 2010-2024, FunctionX Monday 06 December 2021 Next