Home

Introduction to Databases

 

A Database 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 Learning: Introducing Databases

  1. Start Microsoft Visual C#
  2. Create a Windows Forms Application named YugoNationalBank1
  3. In the Solution Explorer, right-click Form1.cs and click Rename
  4. Type Central.cs and press Enter

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:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

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:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

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:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

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

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

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:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

Practical LearningPractical Learning: Creating an Array

  1. To create a new class, on the main menu, click Project -> Add Class...
  2. Set the name to Employee and press Enter
  3. Complete the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace YugoNationalBank1
    {
        public class Employee
        {
            public int EmployeeNumber;
            public string FirstName;
            public string LastName;
            public string Title;
            public bool CanCreateNewAccount;
            public double HourlySalary;
    
            public string FullName
            {
                get { return LastName + ", " + FirstName; }
            }
        }
    }
  4. To create a form that will be used to displays the employees information, on the main menu, click Project -> Add Windows Form
  5. Set the name to Employees and press Enter
  6. Design the form as follows:
     
    Employees
     
    Control Text Name Other Properties
    ListView List View   lvwEmployees FullRowSelect: True
    GridLines: True
    View: Details
    Columns
    (Name) Text TextAlign Width
    colIndex #   20
    colEmployeeNumber Empl #   50
    colFirstName First Name   65
    colLastName Last Name   65
    colFullName Full Name   95
    colTitle Title   145
    colHourlySalary Salary Right 50
    Button Button Close btnClose  
  7. To create a new class, on the main menu, click Project -> Add Class...
  8. Set the name to Customer and press Enter
  9. Complete the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace YugoNationalBank1
    {
        public enum AccountStatus
        {
            Active,
            Suspended,
            Closed
        };
    
        public class Customer
        {
            public string CreatedBy;
            public DateTime DateCreated;
            public string CustomerName;
            public string AccountNumber;
            public string AccountType;
            public AccountStatus Status;
        }
    }
  10. To create a form that will show the customers records, on the main menu, click Project -> Add Windows Form
  11. Set the name to Customers and press Enter
  12. Design the form as follows:
     
    Customers
     
    Control Text Name Other Properties
    ListView List View   lvwCustomers FullRowSelect: True
    GridLines: True
    View: Details
    Columns
    (Name) Text TextAlign Width
    colIndex #   20
    colCreatedBy Created By   100
    colDateCreated Date Created Center 75
    colCustomerName Customer Name   120
    colAccountNumber Account # Center 80
    colAccountType Account Type   80
    coloAccountStatus Status   50
    Button Button Close btnClose  
  13. Double-click the Close button and implement its event as follows:
     
    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
  14. To create a new class, on the main menu, click Project -> Add Class...
  15. Set the name to AccountTransaction and press Enter
  16. Complete the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace YugoNationalBank1
    {
        public enum TransactionTypes
        {
            Deposit,
            Withdrawal,
            Transfer,
            MonthlyCharge,
            MoneyOrder,
            Overdraft,
            TransactionFee
        }
    
        public class AccountTransaction
        {
            public DateTime TransactionDate;
            public int ProcessedBy;
            public string ProcessedFor;
            public TransactionTypes TransactionType;
            public double DepositAmount;
            public double WithdrawalAmount;
            public double ChargeAmount;
        }
    }
  17. To create a new form that will show the transactions done on the customers accounts, on the main menu, click Project -> Add Windows Form
  18. Set the name to CustomersTransactions and press Enter
  19. Design the form as follows:
     
    Customers Transactions
     
    Control Text Name Other Properties
    ListView List View   lvwTransactions FullRowSelect: True
    GridLines: True
    View: Details
    Columns
    (Name) Text TextAlign Width
    colIndex #   25
    colTransactionDate Trans Date Center 80
    colProcessedBy Processed By Center 80
    colProcessedFor Processed For Center 90
    colTransactionType Trans Type   90
    colDepositAmount Deposit Right  
    colWithdrawalAmount Withdrawal Right 65
    colChargeAmount Charge Right 50
    Button Button Close btnClose  
  20. Double-click the Close button and implement its event as follows:
     
    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
  21. To create a new class, on the main menu, click Project -> Add Class...
  22. Set the name to AccountsRecords and press Enter
  23. Complete the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace YugoNationalBank1
    {
        public static class AccountsRecords
        {
            public static Employee[] GetEmployees()
            {
                Employee[] StaffMembers = new Employee[]
                {
                    new Employee()
                    {
                        EmployeeNumber = 74228, FirstName = "Chrissie",
                        LastName = "Nomads", Title = "General Manager",
                        CanCreateNewAccount = true, HourlySalary = 40.25
                    },
    
                    new Employee()
                    {
                        EmployeeNumber = 27905, FirstName = "Calvin",
                        LastName = "Braxton", Title = "Public Relations Manager",
                        CanCreateNewAccount = false, HourlySalary = 25.95  
                    },
         
                    new Employee()
                    {
                        EmployeeNumber = 94805, FirstName = "Emilie",
                        LastName = "Pastore", Title = "Branch Manager",
                        CanCreateNewAccount = true, HourlySalary = 32.55  
                    },
         
                    new Employee()
                    {
                        EmployeeNumber = 39850, FirstName = "Walter",
                        LastName = "Lemme", Title = "Accounts Manager",
                        CanCreateNewAccount = true, HourlySalary = 28.35  
                    },
         
                    new Employee()
                    {
                        EmployeeNumber = 70594, FirstName = "Cecile",
                        LastName = "Richards", Title = "Accounts Representative",
                        CanCreateNewAccount = false, HourlySalary =   18.15 
                    },
          
                    new Employee()
                    {
                        EmployeeNumber = 85285, FirstName = "Joan",
                        LastName = "Verrion", Title = "Accounts Representative",
                        CanCreateNewAccount = false , HourlySalary =  14.85 
                    },
          
                    new Employee()
                    {
                        EmployeeNumber = 94852, FirstName = "Donald",
                        LastName = "Waters", Title = "Accounts Representative",
                        CanCreateNewAccount = false, HourlySalary =   16.45 
                    }
                };
    
                return StaffMembers;
            }
    
            public static Customer[] GetCustomers()
            {
                Customer[] Clients = new Customer[]
                {
                    new Customer()
                    {
                        CreatedBy = "Lemme, Walter", 
    				DateCreated = new DateTime(2007, 1, 16),
                        CustomerName ="Louis George Berholdt", 
    				  AccountNumber = "95-722947-93",
                        AccountType = "Checking", Status = AccountStatus.Active
                    },
                    
                    new Customer()
                    {
                        CreatedBy = "Pastore, Emilie", 
    				DateCreated = new DateTime(2007, 1, 18),
                        CustomerName ="William Foster", 
    		    AccountNumber = "62-384638-48",
                        AccountType = " Checking", Status = AccountStatus.Active
                    },
                    
                    new Customer()
                    {
                        CreatedBy = "Lemme, Walter", 
    				DateCreated = new DateTime(2007, 1, 18),
                        CustomerName ="Catherine Hoods", 
    		    AccountNumber = "92-318284-75",
                        AccountType = "Checking", Status = AccountStatus.Active
                    },
                    
                    new Customer()
                    {
                        CreatedBy = "Lemme, Walter", 
    				DateCreated = new DateTime(2007, 3, 26),
                        CustomerName ="Harriett Cranston", 
    		    AccountNumber = "17-490040-83",
                        AccountType = "Saving", Status = AccountStatus.Active
                    },
    
                    new Customer()
                    {
                        CreatedBy = "Nomads, Chrissie", 
    			DateCreated = new DateTime(2007, 4, 04),
                        CustomerName ="Janice Bonnie Weiss", 
    		    AccountNumber = "58-405048-15",
                        AccountType = "Checking", Status = AccountStatus.Active
                    }
                };
    
                return Clients;
            }
    
            public static AccountTransaction[] GetTransactions()
            {
                AccountTransaction[] Transactions = new AccountTransaction[]
                {
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007, 1,16), 
    		    ProcessedBy = 39850,
                        ProcessedFor = "95-722947-93",
                        TransactionType = TransactionTypes.Deposit, 
    		    DepositAmount = 325.50
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007, 1,18), 
    		    ProcessedBy = 94805,
                        ProcessedFor = "62-384638-48",
                        TransactionType = TransactionTypes.Deposit, 
    		    DepositAmount = 550.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,1,18), 
    		    ProcessedBy = 39850,
                        ProcessedFor = "92-318284-75",
                        TransactionType = TransactionTypes.Deposit, 
    		    DepositAmount = 975.35
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,1,22), 
    		    ProcessedBy = 94852,
                        ProcessedFor = "95-722947-93",
                        TransactionType = TransactionTypes.Withdrawal,
                        WithdrawalAmount = 100.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,1,22), 
    		    ProcessedBy = 70594,
                        ProcessedFor = "62-384638-48",
                        TransactionType = TransactionTypes.Withdrawal,
                        WithdrawalAmount = 122.48
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,1,22), 
    		    ProcessedBy = 94852,
                        ProcessedFor = "92-318284-75",
                        TransactionType = TransactionTypes.Withdrawal,
                        WithdrawalAmount = 214.86
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,1,22), 
    		    ProcessedBy = 85285,
                        ProcessedFor = "62-384638-48",
                        TransactionType = TransactionTypes.Withdrawal,
                        WithdrawalAmount = 140.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,1,24), 
    		    ProcessedBy = 85285,
                        ProcessedFor = "95-722947-93",
                        TransactionType = TransactionTypes.MoneyOrder,
                        WithdrawalAmount = 116.24
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,1,24),
                        ProcessedFor = "95-722947-93",
                        TransactionType = TransactionTypes.TransactionFee,
                        ChargeAmount = 1.45
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,1,30), 
    		    ProcessedBy = 70594,
                        ProcessedFor = "62-384638-48",
                        TransactionType = TransactionTypes.Withdrawal,
                        WithdrawalAmount = 40.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,1,30),
                        ProcessedFor = "95-722947-93",
                        TransactionType = TransactionTypes.MonthlyCharge,
                        ChargeAmount = 6.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,1,30),
                        ProcessedFor = "92-318284-75",
                        TransactionType = TransactionTypes.MonthlyCharge,
                        ChargeAmount = 6.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,1,30),
                        ProcessedFor = "62-384638-48",
                        TransactionType = TransactionTypes.MonthlyCharge,
                        ChargeAmount = 6.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,2,06), 
    		    ProcessedBy = 85285,
                        ProcessedFor = "92-318284-75",
                        TransactionType = TransactionTypes.Withdrawal,
                        WithdrawalAmount = 42.35
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,2,06), 
    		    ProcessedBy = 70594,
                        ProcessedFor = "95-722947-93",
                        TransactionType = TransactionTypes.Withdrawal,
                        WithdrawalAmount = 115.00 
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,2,06), 
    		    ProcessedBy = 94852,
                        ProcessedFor = "62-384638-48",
                        TransactionType = TransactionTypes.Withdrawal,
                        WithdrawalAmount = 64.14
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,2,28),
                        ProcessedFor = "95-722947-93",
                        TransactionType = TransactionTypes.MonthlyCharge, 
    		    ChargeAmount = 6.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,2,28),
                        ProcessedFor = "95-722947-93",
                        TransactionType = TransactionTypes.Overdraft,
                        WithdrawalAmount = 35.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,2,28),
                        ProcessedFor = "62-384638-48",
                        TransactionType = TransactionTypes.MonthlyCharge, 
    		    ChargeAmount = 6.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,2,28),
                        ProcessedFor = "92-318284-75",
                        TransactionType = TransactionTypes.MonthlyCharge, 
    		    ChargeAmount = 6.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,3,15), 
    		    ProcessedBy = 70594,
                        ProcessedFor = "95-722947-93",
                        TransactionType = TransactionTypes.Withdrawal,
                        WithdrawalAmount = 200.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,3,26), 
    		    ProcessedBy = 39850,
                        ProcessedFor = "17-490040-83",
                        TransactionType = TransactionTypes.Deposit,
                        DepositAmount = 1000.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,4,4), 
    		    ProcessedBy = 74228,
                        ProcessedFor = "58-405048-15",
                        TransactionType = TransactionTypes.Deposit,
                        DepositAmount = 126.85
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,4,6), 
    		    ProcessedBy = 85285,
                        ProcessedFor = "92-318284-75",
                        TransactionType = TransactionTypes.Deposit,
                        DepositAmount = 250.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,4,6), 
    		    ProcessedBy = 70594,
                        ProcessedFor = "62-384638-48",
                        TransactionType = TransactionTypes.Deposit,
                        DepositAmount = 400.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,4,12), 
    		    ProcessedBy = 94852,
                        ProcessedFor = "95-722947-93",
                        TransactionType = TransactionTypes.Deposit,
                        DepositAmount = 100.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,4,30),
                        ProcessedFor = "58-405048-15",
                        TransactionType = TransactionTypes.MonthlyCharge,
                        ChargeAmount = 6.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,4,30),
                        ProcessedFor = "62-384638-48",
                        TransactionType = TransactionTypes.MonthlyCharge,
                        ChargeAmount = 6.00 
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,4,30),
                        ProcessedFor = "92-318284-75",
                        TransactionType = TransactionTypes.MonthlyCharge,
                        ChargeAmount = 6.00
                    },
                    new AccountTransaction()
                    {
                        TransactionDate = new DateTime(2007,4,30),
                        ProcessedFor = "17-490040-83",
                        TransactionType = TransactionTypes.MonthlyCharge,
                        ChargeAmount = 6.00
                    }
                };
    
                return Transactions;
            }
        }
    }
  24. Access the Central form and a button to it
  25. Change the properties of the button as follows:
    (Name): btnEmployees
    Text:     Employees
  26. Double-click the Employees button and implement its event as follows:
     
    private void btnEmployees_Click(object sender, EventArgs e)
    {
        int i = 1;
        Employees frmEmployees = new Employees();
        Employee[] StaffMembers = AccountsRecords.GetEmployees();
    
        frmEmployees.lvwEmployees.Items.Clear();
    
        foreach (Employee empl in StaffMembers)
        {
            ListViewItem lviEmployee = new ListViewItem(i.ToString());
    
            lviEmployee.SubItems.Add(empl.EmployeeNumber.ToString());
            lviEmployee.SubItems.Add(empl.FirstName);
            lviEmployee.SubItems.Add(empl.LastName);
            lviEmployee.SubItems.Add(empl.FullName);
            lviEmployee.SubItems.Add(empl.Title);
            lviEmployee.SubItems.Add(empl.HourlySalary.ToString("F"));
    
            frmEmployees.lvwEmployees.Items.Add(lviEmployee);
            i++;
        }
    
        frmEmployees.ShowDialog();
    }
  27. Return to the Central form and a button to it
  28. Change the properties of the button as follows:
    (Name): btnCustomers
    Text:     Customers
  29. Double-click the Employees button and implement its event as follows:
     
    private void btnCustomers_Click(object sender, EventArgs e)
    {
        int i = 1;
        Customers frmCustomers = new Customers();
        Customer[] Clients = AccountsRecords.GetCustomers();
    
        frmCustomers.lvwCustomers.Items.Clear();
    
        foreach (Customer client in Clients)
        {
            ListViewItem lviCustomer = new ListViewItem(i.ToString());
    
            lviCustomer.SubItems.Add(client.CreatedBy);
            lviCustomer.SubItems.Add(client.DateCreated.ToShortDateString());
            lviCustomer.SubItems.Add(client.CustomerName);
            lviCustomer.SubItems.Add(client.AccountNumber);
            lviCustomer.SubItems.Add(client.AccountType);
            lviCustomer.SubItems.Add(client.Status.ToString());
    
            frmCustomers.lvwCustomers.Items.Add(lviCustomer);
            i++;
        }
    
        frmCustomers.ShowDialog();
    }
  30. Return to the Central form and a button to it
  31. Change the properties of the button as follows:
    (Name): btnTransactions
    Text:     Transactions
  32. Double-click the Employees button and implement its event as follows:
     
    private void btnTransactions_Click(object sender, EventArgs e)
    {
        int i = 1;
        CustomersTransactions frmTransactions = new CustomersTransactions();
        AccountTransaction[] Transactions = AccountsRecords.GetTransactions();
    
        frmTransactions.lvwTransactions.Items.Clear();
    
        foreach (AccountTransaction ActTrans in Transactions)
        {
            ListViewItem lviTransactions = new ListViewItem(i.ToString());
    
            lviTransactions.SubItems.Add(
    		ActTrans.TransactionDate.ToString("dd-MMM-yyyy") );
    
            if(ActTrans.ProcessedBy == 0 )
                lviTransactions.SubItems.Add("");
            else
                lviTransactions.SubItems.Add(ActTrans.ProcessedBy.ToString());
    
            lviTransactions.SubItems.Add(ActTrans.ProcessedFor);
            lviTransactions.SubItems.Add(ActTrans.TransactionType.ToString());
    
            if(ActTrans.DepositAmount == 0)
                lviTransactions.SubItems.Add("");
            else
                lviTransactions.SubItems.Add(
    		ActTrans.DepositAmount.ToString("F"));
    
            if (ActTrans.WithdrawalAmount == 0)
                lviTransactions.SubItems.Add("");
            else
                lviTransactions.SubItems.Add(
    		ActTrans.WithdrawalAmount.ToString("F"));
    
            if (ActTrans.ChargeAmount == 0)
                lviTransactions.SubItems.Add("");
            else
                lviTransactions.SubItems.Add(
    		ActTrans.ChargeAmount.ToString("F"));
    
            frmTransactions.lvwTransactions.Items.Add(lviTransactions);
            i++;
        }
    
        frmTransactions.ShowDialog();
    }
  33. Execute the application to see the results
  34. Close the forms and return to your programming environment

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:

  • Adding elements to the array
  • Re-arranging the list or the order of elements in the array.
  • Finding out whether the array contains a certain element
  • If the array contains a certain element, what index that element has

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.

Practical Learning: Introducing Operations on Arrays

  1. To create a new form, on the main menu, click Project -> Add Windows Form
  2. Set the name to CustomerTransactions and press Enter
  3. Design the form as follows:
     
    Customer Transactions
     
    Control Text Name Other Properties
    Label Label View Transactions For:    
    MaskedTextBox MaskedTextBox   txtAccountNumber Mask: 00-000000-00
    Button Button Find btnFind  
    ListView List View   lvwCustomers FullRowSelect: True
    GridLines: True
    View: Details
    Columns
    (Name) Text TextAlign Width
    colIndex #   25
    colTransactionDate Trans Date Center 80
    colProcessedBy Processed By Center 80
    colTransactionType Trans Type   90
    colDeposit Deposit Right  
    colWithdrawal Withdrawal Right 65
    colChargeAmount Charge Right 50
    Button Button Close btnClose  
  4. Save all

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:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

 

Practical Learning: Checking the Existence of an Element

  1. On the Account Transactions form, double-click the Find button and change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace YugoNationalBank1
    {
        public partial class CustomerTransactions : Form
        {
            static string AccountNumber;
    
            public CustomerTransactions()
            {
                InitializeComponent();
            }
    
            private static bool AccountNumberExists(Customer Client)
            {
                if(Client.AccountNumber == AccountNumber)
                    return true;
                else
                    return false;
            }
    
            private void btnFind_Click(object sender, EventArgs e)
            {
                AccountNumber = txtAccountNumber.Text;
                Customer[] Accounts = AccountsRecords.GetCustomers();
    
                if (Array.Exists<Customer>(Accounts, AccountNumberExists))
                {
                    MessageBox.Show("Good");
                }
                else
                    MessageBox.Show(
    		    "There is no customer with that account number");
            }
        }
    }
  2. Display the Central form and complete its design as follows:
     
    Button Text Name
    Button Employees btnEmployees
    Button Customers btnCustomers
    Button Transactions btnTransactions
    Button Customer Records btnCustomerRecords
    Button Close btnClose
  3. Double-click the Customer Records button and implement its event as follows:
     
    private void btnCustomerRecords_Click(object sender, EventArgs e)
    {
        CustomerTransactions CustRecords = new CustomerTransactions();
        CustRecords.ShowDialog();
    }
  4. Return to the Central form and double-click the Close button
  5. Implement its event as follows:
     
    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
  6. Execute the application to test it
  7. Close the forms and return to your programming environment

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

Practical Learning: Finding an Element

  1. Access the CustomerTransactions.cs source code and change the Click event of the Find button as follows:
     
    private void btnFind_Click(object sender, EventArgs e)
    {
        /*
        AccountNumber = txtAccountNumber.Text;
        Customer[] Accounts = AccountsRecords.GetCustomers();
    
        if (Array.Exists<Customer>(Accounts, AccountNumberExists))
        {
            MessageBox.Show("Good");
        }
        else
            MessageBox.Show("There is no customer with that account number");*/
    
        double TotalDeposits = 0;
        double TotalWithdrawals = 0;
        double TotalCharges = 0;
        double Balance;
    
        AccountNumber = txtAccountNumber.Text;
        Customer[] Accounts = AccountsRecords.GetCustomers();
        AccountTransaction[] Trans = AccountsRecords.GetTransactions();
        bool AccountFound = 
    	 Array.Exists<Customer>(Accounts, AccountNumberExists);
    
        if (AccountFound == true)
        {
            int i = 1;
            lvwTransactions.Items.Clear();
    
            foreach (AccountTransaction ActTrans in Trans)
            {
                if (ActTrans.ProcessedFor == AccountNumber)
                {
                    ListViewItem lviTransactions = 
    			new ListViewItem(i.ToString());
    
                    lviTransactions.SubItems.Add(
    			ActTrans.TransactionDate.ToString("dd-MMM-yyyy"));
    
                    if (ActTrans.ProcessedBy == 0)
                        lviTransactions.SubItems.Add("");
                    else
                        lviTransactions.SubItems.Add(
    			ActTrans.ProcessedBy.ToString());
    
                    lviTransactions.SubItems.Add(
    			ActTrans.TransactionType.ToString());
    
                    if (ActTrans.DepositAmount == 0)
                        lviTransactions.SubItems.Add("");
                    else
                        lviTransactions.SubItems.Add(
    			ActTrans.DepositAmount.ToString("F"));
    
                    if (ActTrans.WithdrawalAmount == 0)
                        lviTransactions.SubItems.Add("");
                    else
                        lviTransactions.SubItems.Add(
    			ActTrans.WithdrawalAmount.ToString("F"));
    
                    if (ActTrans.ChargeAmount == 0)
                        lviTransactions.SubItems.Add("");
                    else
                        lviTransactions.SubItems.Add(
    			ActTrans.ChargeAmount.ToString("F"));
    
                    lvwTransactions.Items.Add(lviTransactions);
    
                    i++;
                }
            }
    
            foreach (ListViewItem lviTransaction in lvwTransactions.Items)
            {
                if( lviTransaction.SubItems[4].Text != "" )
                    TotalDeposits = TotalDeposits + 
    			double.Parse(lviTransaction.SubItems[4].Text);
                if( lviTransaction.SubItems[5].Text != "" )
                    TotalWithdrawals = TotalWithdrawals + 
    			double.Parse(lviTransaction.SubItems[5].Text);
                if( lviTransaction.SubItems[6].Text != "" )
                    TotalCharges = TotalCharges + 
    			double.Parse(lviTransaction.SubItems[6].Text);
            }
    
            Balance = TotalDeposits - (TotalWithdrawals + TotalCharges);
            txtTotalDeposits.Text = TotalDeposits.ToString("F");
            txtTotalWithdrawals.Text = TotalWithdrawals.ToString("F");
            txtTotalCharges.Text = TotalCharges.ToString("F");
            txtBalance.Text = Balance.ToString("F");
        }
        else
            MessageBox.Show("There is no customer with that account number");
    }
  2. Return to the Account Transactions form and double-click the Close button
  3. Implement its event as follows:
     
    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
  4. Execute the application to test it

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:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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 a get 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:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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.

 

Home Copyright © 2008-2010 FunctionX, Inc.