Home

The Array Class

 
 

Types of Arrays

 

Single-Dimensional Array Creation

An array is a technique of storing information of different items in a common variable of one name. For example, consider the following list:

Store Item
Women Coat
Men Jacket
Teen Jeans
Women Bathing Suit
Children Playground Dress

This type of list can be created using a string-based array. Here is an example:

using System;

class CSharpCollections
{
    static int Main()
    {
	string[] lstItemsNames = { "Women Coat", "Men Jacket", "Teen Jeans",
			 "Women Bathing Suit", "Children Playground Dress" };

	return 0;
    }
}

The above type of list is referred to as a single-dimensional. To provide more information about items, you can associate a second or even a third list to the first as follows:

using System;

class CSharpCollections
{
    static int Main()
    {
	string[] itemsNumbers = { "624376", "274952", "497852", "749752", "394085" };
	string[] lstItemsNames    = { "Women Coat", "Men Jacket", "Teen Jeans",
				"Women Bathing Suit", "Children Playground Dress" };
	double[] itemsPrices      = { 225.55, 175.75, 24.50, 34.65, 75.05 };

	return 0;
    }
}

To support arrays, the .NET Framework provides the Array class, which is defined in the System namespace. Based on this, you can formally use the Array class to create an array. To support the creation of an array, the Array class is equipped with the CreateInstance() method that comes in various versions. To create a one-dimensional array, you can use the following version:

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

The first argument is used to specify the type of array you want to create. Since it is declared as Type, you can use the typeof operator to cast your type.

The second argument specifies the number of items of the list. The items in an Array-based list use a zero-based index, meaning that the first item has an index of 0, the second has an index of 1, and so on. Using the Array class, you can create a list of the above item names as follows:

using System;

class CSharpCollections
{
    static int Main()
    {
	Array lstItemsNames = Array.CreateInstance(typeof(string), length);

	return 0;
    }
}

Creating various lists that would be later connected can be confusing and even overwhelming, as mentioned earlier.

 

Practical Learning Practical Learning: Creating a List Class

  1. Start Notepad and, in the empty file, type the following:
     
    using System;
    
    namespace StoreItem
    {
    	public class CStoreItem
    	{
    		private	string nbr;
    		private	string nm;
    		private	string sz;
    		private	double uprice;
    		
    		public CStoreItem()
    		{
    			nbr = "";
    			nm  = "";
    			sz  = "";
    			uprice = 0.00;
    		}
    
    		CStoreItem(string number, string name, string size, double price)
    		{
    			nbr    = number;
    			nm     = name;
    			sz     = size;
    			uprice = price;
    		}
    
    		public string ItemNumber
    		{
    			get { return nbr; }
    			set { nbr = value; }
    		}
    
    		public string ItemName
    		{
    			get { return nm; }
    			set { nm = value; }
    		}
    
    		public string Size
    		{
    			get { return sz; }
    			set { sz = value; }
    		}
    
    		public double UnitPrice
    		{
    			get {return uprice; }
    			set { uprice = value ; }
    		}
    	}
    }
  2. To save the file, on the main menu of Notepad, click File -> Save...
  3. Locate your C:, D:, or any drive and display it in the Save In combo box
  4. If you have a folder named CSharpWindows, double-click it to display it in the Save In combo box.
    If you don't have it, click the Create New Folder button, type CSharpWindows and press Enter twice to display it in the Save In combo
  5. Click the Create New Folder button, type DepartmentStore1 and press Enter twice to display it in the Save In combo
  6. Change the Files of Type to All Files and change the File Name to StoreItem.cs
  7. Click Save
  8. Open the Command Prompt and switch to the above DepartmentStore1 folder
  9. To create the library, type csc /target:library StoreItem.cs and press Enter
  10. To start a new file, on the main menu of Notepad, click File -> New
  11. In the empty file, type:
      
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    namespace DepartmentStore1
    {
    	public class Exercise : System.Windows.Forms.Form
    	{
    		private System.Windows.Forms.Label lblItemNumber;
    		private System.Windows.Forms.TextBox txtItemNumber;
    		private System.Windows.Forms.Label lblDescription;
    		private System.Windows.Forms.TextBox txtDescription;
    		private System.Windows.Forms.Label lblItemSize;
    		private System.Windows.Forms.TextBox txtSize;
    		private System.Windows.Forms.Label lblUnitPrice;
    		private System.Windows.Forms.TextBox txtUnitPrice;
    		private System.Windows.Forms.Button btnClose;
    		private System.Windows.Forms.Button btnFirst;
    		private System.Windows.Forms.Button btnPrevious;
    		private System.Windows.Forms.Button btnNext;
    		private System.Windows.Forms.Button btnLast;
    
    		public Exercise()
    		{
    			InitializeComponent();
    		}
    
    		private void InitializeComponent()
    		{
    			this.lblItemNumber = new System.Windows.Forms.Label();
    			this.txtItemNumber = new System.Windows.Forms.TextBox();
    			this.lblDescription = new System.Windows.Forms.Label();
    			this.txtDescription = new System.Windows.Forms.TextBox();
    			this.lblItemSize = new System.Windows.Forms.Label();
    			this.txtSize = new System.Windows.Forms.TextBox();
    			this.lblUnitPrice = new System.Windows.Forms.Label();
    			this.txtUnitPrice = new System.Windows.Forms.TextBox();
    			this.btnClose = new System.Windows.Forms.Button();
    			this.btnFirst = new System.Windows.Forms.Button();
    			this.btnPrevious = new System.Windows.Forms.Button();
    			this.btnNext = new System.Windows.Forms.Button();
    			this.btnLast = new System.Windows.Forms.Button();
    
    			// Label: ItemNumber
    			this.lblItemNumber.Location = new System.Drawing.Point(16, 18);
    			this.lblItemNumber.Size = new System.Drawing.Size(56, 16);
    			this.lblItemNumber.TabIndex = 1;
    			this.lblItemNumber.Text = "Item #:";
    
    			// TextBox ItemNumber
    			this.txtItemNumber.Location = new System.Drawing.Point(96, 16);
    			this.txtItemNumber.Size = new System.Drawing.Size(80, 20);
    			this.txtItemNumber.TabIndex = 2;
    			this.txtItemNumber.Text = "";
    
    			// Label: Description
    			this.lblDescription.Location = new System.Drawing.Point(16, 51);
    			this.lblDescription.Size = new System.Drawing.Size(72, 16);
    			this.lblDescription.TabIndex = 3;
    			this.lblDescription.Text = "Description:";
    
    			// TextBox: Description
    			this.txtDescription.Location = new System.Drawing.Point(96, 48);
    			this.txtDescription.Size = new System.Drawing.Size(232, 20);
    			this.txtDescription.TabIndex = 4;
    			this.txtDescription.Text = "";
    			
    			// Label: Item Size
    			this.lblItemSize.Location = new System.Drawing.Point(16, 82);
    			this.lblItemSize.Name = "lblItemSize";
    			this.lblItemSize.Size = new System.Drawing.Size(72, 16);
    			this.lblItemSize.TabIndex = 5;
    			this.lblItemSize.Text = "Item Size:";
    		
    			// TextBox: Size
    			this.txtSize.Location = new System.Drawing.Point(96, 80);
    			this.txtSize.Name = "txtSize";
    			this.txtSize.Size = new System.Drawing.Size(80, 20);
    			this.txtSize.TabIndex = 6;
    			this.txtSize.Text = "";
    
    			// Label: UnitPrice
    			this.lblUnitPrice.Location = new System.Drawing.Point(192, 83);
    			this.lblUnitPrice.Size = new System.Drawing.Size(56, 16);
    			this.lblUnitPrice.TabIndex = 7;
    			this.lblUnitPrice.Text = "Unit Price:";
    
    			// TextBox: UnitPrice
    			this.txtUnitPrice.Location = new System.Drawing.Point(256, 80);
    			this.txtUnitPrice.Size = new System.Drawing.Size(72, 20);
    			this.txtUnitPrice.TabIndex = 8;
    			this.txtUnitPrice.Text = "";
    			this.txtUnitPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
    	
    			// Button: Close
    			this.btnClose.Location = new System.Drawing.Point(16, 112);
    			this.btnClose.TabIndex = 9;
    			this.btnClose.Text = "Close";
    			this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
    			
    			// Button: First
    			this.btnFirst.Location = new System.Drawing.Point(96, 112);
    			this.btnFirst.Name = "btnFirst";
    			this.btnFirst.Size = new System.Drawing.Size(48, 23);
    			this.btnFirst.TabIndex = 10;
    			this.btnFirst.Text = "| <";
    		
    			// Button: Previous
    			this.btnPrevious.Location = new System.Drawing.Point(144, 112);
    			this.btnPrevious.Name = "btnPrevious";
    			this.btnPrevious.Size = new System.Drawing.Size(48, 23);
    			this.btnPrevious.TabIndex = 11;
    			this.btnPrevious.Text = "<<";
    
    			// Button: Next
    			this.btnNext.Location = new System.Drawing.Point(232, 112);
    			this.btnNext.Size = new System.Drawing.Size(48, 23);
    			this.btnNext.TabIndex = 12;
    			this.btnNext.Text = ">>";
    
    			// Button: Last
    			this.btnLast.Location = new System.Drawing.Point(280, 112);
    			this.btnLast.Size = new System.Drawing.Size(48, 23);
    			this.btnLast.TabIndex = 13;
    			this.btnLast.Text = "> |";
    
    			// Form: Exercise
    			this.Controls.Add(this.btnClose);
    			this.Controls.Add(this.btnLast);
    			this.Controls.Add(this.btnNext);
    			this.Controls.Add(this.btnPrevious);
    			this.Controls.Add(this.btnFirst);
    			this.Controls.Add(this.txtUnitPrice);
    			this.Controls.Add(this.lblUnitPrice);
    			this.Controls.Add(this.txtSize);
    			this.Controls.Add(this.lblItemSize);
    			this.Controls.Add(this.txtDescription);
    			this.Controls.Add(this.lblDescription);
    			this.Controls.Add(this.txtItemNumber);
    			this.Controls.Add(this.lblItemNumber);
    
    			this.Size = new System.Drawing.Size(352, 184);
    			this.MaximizeBox = false;
    			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
    			this.Text = "Department Store";
    		}
    
    		private void btnClose_Click(object sender, System.EventArgs e)
    		{
    			Close();
    		}
    		
    		static int Main() 
    		{
    			Application.Run(new Exercise());
    
    			return 0;
    		}
    	}
    }
  12. To save the file, on the main menu of Notepad, click File -> Save...
  13. Locate the DepartmentStore1 folder and display it in the Save In combo box
  14. Change the Files Of Type to All Files
  15. Change the File Name to Exercise.cs 
  16. Click Save
  17. Return to the Command Prompt. To compile the exercise, type csc Exercise.cs and press Enter
  18. To execute the application, type Exercise and press Enter
     
  19. Close the form and return to Notepad

The Length of an Array

When creating an array that you are not initializing, you must provide the number of items that the list will contain. This number is passed inside the variable's square brackets as a constant integer. Here is an example:

private void Form1_Load(object sender, System.EventArgs e)
{
	string[] lstItemsNames = new string[5];
}

If you create a list using the Array.CreateInstance() method using the above version, you must pass a constant integer as the second argument. Here is an example:

private void Form1_Load(object sender, System.EventArgs e)
{
	Array lstItemsNames = Array.CreateInstance(typeof(string), 5);
}

If the array exists already, to find out the number of items it contains, you can access its Length property. Alternatively, you can call the Array.GetLength() method. Its syntax is:

public int GetLength(int dimension);

For a single dimensional array as those declared above, you must pass the argument as 0. This method returns a 32-bit integer that represents the number of items in the array.

 

 

Two-Dimensional Array Creation

The type of array we declared earlier is referred to as a single-dimensional. To provide more information about items, you can associate a second or even a third list to the first as follows:

private void Form1_Load(object sender, System.EventArgs e)
{
	string[] lstItemsNames    = { "Women Coat", "Men Jacket", "Teen Jeans",
		                              "Women Bathing Suit", "Children Playground Dress" };
}

You can create a two-dimensional array by entering a comma in the square brackets of the array variable and two constant integers separated by a comma when allocating memory for the array. Here is an example:

private void Form1_Load(object sender, System.EventArgs e)
{
	string[,] lstItemsNames = new string[2,3];
}

If you want to use the Array.CreateInstance() method to create a two-dimensional array, you can use the following version:

public static Array CreateInstance(Type elementType, int length1, int length2);

A two-dimensional array is also called an array of two arrays. If using the classic technique of declaring an array, the first number specified when allocating memory, in the above example it would be 2, represents the number of arrays. This is the same number of the second argument of the current CreateInstance() method. For a two-dimensional array, this number is always 2. The second number of the classic declaration and the third argument of the current CreateInstance() method specify the number of items that each list would contain. In the above declaration, the number 3 means that each array will be made of three items.

Based on this, here is an example of declaring a two-dimensional array using the CreateInstance() method:

private void Form1_Load(object sender, System.EventArgs e)
{
	string[,] lstItemsNames = new string[2,3];
	Array lstItemsNumbers = Array.CreateInstance(typeof(string), 2, 3);
}

To know the total number of items that an array contains, you can access its Length property. To know the number of items that a particular list contains, call the Array.GetLength() method and pass the number corresponding to the array. To know the number of items in the first list, pass the argument as 0. To know the number of items in the second list, pass the argument as 1.

Multidimensional Array Creation

Besides the single or two-dimensional, you can create multidimensional arrays by specifying the number of commas in the square brackets and specifying the numbers in the right square brackets. If you want to use the Array.CreateInstance() method to create a multidimensional array, you can call the following version:

public static Array CreateInstance(Type elementType, params int[] lengths);

With this version of the method, the second argument specifies the number of arrays that the variable will hold.

If you want to find out the total number of items that an array contains, access its Length property. To get the number of items that a particular list contains, you can call the Array.GetLength() method and pass the number corresponding to the array.

To know the number of lists that an array variable contains, you can access its Rank property.

 

Operations on Arrays

 

Adding Items to an Array

There are two main techniques you can use to initialize an array. You can create its list of items when declaring the array. Here is an example:

private void Form1_Load(object sender, System.EventArgs e)
{
	double[] itemsPrices = { 225.55, 175.75, 24.50, 34.65, 75.05 };
}

Another technique is to first declare the array, then initialize each of its members. Here is an example:

private void Form1_Load(object sender, System.EventArgs e)
{
	string[] storeItems = new string[4];
				 
	storeItems[0] = "Women Coat";
	storeItems[1] = "Women Bathing Suit";
	storeItems[2] = "Quilted Down Jacket";
	storeItems[3] = "Men Jacket";
}

Here is an example for a two-dimensional array:

private void Form1_Load(object sender, System.EventArgs e)
{
	string[,] storeItems = new string[2,3];
				 
	storeItems[0,0] = "Women Coat";
	storeItems[0,1] = "Women Bathing Suit";
	storeItems[0,2] = "Quilted Down Jacket";
	storeItems[1,0] = "Men Jacket";
	storeItems[1,1] = "Children Playground Dress";
	storeItems[1,2] = "Boys Trousers";
}

The Array class also provides its own support for adding items to an array. This is done using the Array.SetValue() that is overloaded with various versions. To add a new item to a single-dimensional array, you can use the following syntax:

public void SetValue(Object value, int index);

The first argument is the value to add to the list. The second argument is the index of the item to be added. The first item has index 1; the second item has index 2, and so on. Here is an example:

private void Form1_Load(object sender, System.EventArgs e)
{
	string[] storeItems = new string[4];
				 
	storeItems.SetValue("Women Coat", 0);
	storeItems.SetValue("Women Bathing Suit", 1);
	storeItems.SetValue("Quilted Down Jacket", 2);
	storeItems.SetValue("Men Jacket", 3);
}

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

Practical Learning Practical Learning: Adding Items to an Array

  1. To populate the array, change the Load event as follows:
     
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using StoreItem;
    
    namespace DepartmentStore1
    {
    	public class Exercise : System.Windows.Forms.Form
    	{
    		. . . No Change
    
    		Array lstItemsInStore;
    
    		public Exercise()
    		{
    			InitializeComponent();
    		}
    
    		private void InitializeComponent()
    		{
    			. . . No Change
    
    			
    
    			this.Load += new System.EventHandler(this.Exercise_Load);
    
    		}
    
    		private void Exercise_Load(object sender, System.EventArgs e)
    		{
    			lstItemsInStore = Array.CreateInstance(typeof(CStoreItem), 6);
    
    			CStoreItem anItem = new CStoreItem();
    			anItem.ItemNumber = "724372";
    			anItem.ItemName   = "Women Coat";
    			anItem.Size       = "Large";
    			anItem.UnitPrice  = 225.55;
    			lstItemsInStore.SetValue(anItem, 0);
    
    			anItem = new StoreItem.CStoreItem();
    			anItem.ItemNumber = "624376";
    			anItem.ItemName   = "Men Jacket";
    			anItem.Size       = "Medium";
    			anItem.UnitPrice  = 175.75;
    			lstItemsInStore.SetValue(anItem, 1);
    
    			anItem = new StoreItem.CStoreItem();
    			anItem.ItemNumber = "274952";
    			anItem.ItemName   = "Teen Jeans";
    			anItem.Size       = "14";
    			anItem.UnitPrice  = 24.50;
    			lstItemsInStore.SetValue(anItem, 2);
    
    			anItem = new StoreItem.CStoreItem();
    			anItem.ItemNumber = "497852";
    			anItem.ItemName   = "Women Bathing Suit";
    			anItem.Size       = "Petite";
    			anItem.UnitPrice  = 34.65;
    			lstItemsInStore.SetValue(anItem, 3);
    
    			anItem = new StoreItem.CStoreItem();
    			anItem.ItemNumber = "749752";
    			anItem.ItemName   = "Children Playground Dress";
    			anItem.Size       = "12";
    			anItem.UnitPrice  = 75.05;
    			lstItemsInStore.SetValue(anItem, 4);
    
    			anItem = new StoreItem.CStoreItem();
    			anItem.ItemNumber = "394085";
    			anItem.ItemName   = "Boys Trousers";
    			anItem.Size       = "8";
    			anItem.UnitPrice  = 17.95;
    			lstItemsInStore.SetValue(anItem, 5);
    		}
    
    		static int Main() 
    		{
    			Application.Run(new Exercise());
    
    			return 0;
    		}
    	}
    }
  2. Save the file

Accessing the Members of an Array

Probably the most regularly performed operation on a list consists of retrieving the values of its members. You access the member of an array using its index as we saw earlier. To perform the same operation, the Array class is equipped with the GetValue() method that is overloaded with a version corresponding to each version of the CreateInstance() and the SetValue() methods. For example, to access the values stored in a one-dimensional array, you can call call this version:

public object GetValue(int index);

The argument is the zero-based index of the member whose value you want to access. If you pass an invalid value, the computer would throw an IndexOutOfRangeException exception.

Practical Learning Practical Learning: Accessing the Members of an Array

  1. Change the file as follows:
       
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using StoreItem;
    
    namespace DepartmentStore1
    {
    	public class Exercise : System.Windows.Forms.Form
    	{
    		private System.Windows.Forms.Label lblItemNumber;
    		private System.Windows.Forms.TextBox txtItemNumber;
    		private System.Windows.Forms.Label lblDescription;
    		private System.Windows.Forms.TextBox txtDescription;
    		private System.Windows.Forms.Label lblItemSize;
    		private System.Windows.Forms.TextBox txtSize;
    		private System.Windows.Forms.Label lblUnitPrice;
    		private System.Windows.Forms.TextBox txtUnitPrice;
    		private System.Windows.Forms.Button btnClose;
    		private System.Windows.Forms.Button btnFirst;
    		private System.Windows.Forms.Button btnPrevious;
    		private System.Windows.Forms.Button btnNext;
    		private System.Windows.Forms.Button btnLast;
    
    		Array lstItemsInStore;
    		int CurrentPosition;
    
    		public Exercise()
    		{
    			InitializeComponent();
    		}
    
    		private void InitializeComponent()
    		{
    			this.lblItemNumber = new System.Windows.Forms.Label();
    			this.txtItemNumber = new System.Windows.Forms.TextBox();
    			this.lblDescription = new System.Windows.Forms.Label();
    			this.txtDescription = new System.Windows.Forms.TextBox();
    			this.lblItemSize = new System.Windows.Forms.Label();
    			this.txtSize = new System.Windows.Forms.TextBox();
    			this.lblUnitPrice = new System.Windows.Forms.Label();
    			this.txtUnitPrice = new System.Windows.Forms.TextBox();
    			this.btnClose = new System.Windows.Forms.Button();
    			this.btnFirst = new System.Windows.Forms.Button();
    			this.btnPrevious = new System.Windows.Forms.Button();
    			this.btnNext = new System.Windows.Forms.Button();
    			this.btnLast = new System.Windows.Forms.Button();
    
    			// Label: ItemNumber
    			this.lblItemNumber.Location = new System.Drawing.Point(16, 18);
    			this.lblItemNumber.Size = new System.Drawing.Size(56, 16);
    			this.lblItemNumber.TabIndex = 1;
    			this.lblItemNumber.Text = "Item #:";
    
    			// TextBox ItemNumber
    			this.txtItemNumber.Location = new System.Drawing.Point(96, 16);
    			this.txtItemNumber.Size = new System.Drawing.Size(80, 20);
    			this.txtItemNumber.TabIndex = 2;
    			this.txtItemNumber.Text = "";
    
    			// Label: Description
    			this.lblDescription.Location = new System.Drawing.Point(16, 51);
    			this.lblDescription.Size = new System.Drawing.Size(72, 16);
    			this.lblDescription.TabIndex = 3;
    			this.lblDescription.Text = "Description:";
    
    			// TextBox: Description
    			this.txtDescription.Location = new System.Drawing.Point(96, 48);
    			this.txtDescription.Size = new System.Drawing.Size(232, 20);
    			this.txtDescription.TabIndex = 4;
    			this.txtDescription.Text = "";
    			
    			// Label: Item Size
    			this.lblItemSize.Location = new System.Drawing.Point(16, 82);
    			this.lblItemSize.Name = "lblItemSize";
    			this.lblItemSize.Size = new System.Drawing.Size(72, 16);
    			this.lblItemSize.TabIndex = 5;
    			this.lblItemSize.Text = "Item Size:";
    		
    			// TextBox: Size
    			this.txtSize.Location = new System.Drawing.Point(96, 80);
    			this.txtSize.Name = "txtSize";
    			this.txtSize.Size = new System.Drawing.Size(80, 20);
    			this.txtSize.TabIndex = 6;
    			this.txtSize.Text = "";
    
    			// Label: UnitPrice
    			this.lblUnitPrice.Location = new System.Drawing.Point(192, 83);
    			this.lblUnitPrice.Size = new System.Drawing.Size(56, 16);
    			this.lblUnitPrice.TabIndex = 7;
    			this.lblUnitPrice.Text = "Unit Price:";
    
    			// TextBox: UnitPrice
    			this.txtUnitPrice.Location = new System.Drawing.Point(256, 80);
    			this.txtUnitPrice.Size = new System.Drawing.Size(72, 20);
    			this.txtUnitPrice.TabIndex = 8;
    			this.txtUnitPrice.Text = "";
    			this.txtUnitPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
    
    	
    			// Button: Close
    			this.btnClose.Location = new System.Drawing.Point(16, 112);
    			this.btnClose.TabIndex = 9;
    			this.btnClose.Text = "Close";
    			this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
    			
    			// Button: First
    			this.btnFirst.Location = new System.Drawing.Point(96, 112);
    			this.btnFirst.Name = "btnFirst";
    			this.btnFirst.Size = new System.Drawing.Size(48, 23);
    			this.btnFirst.TabIndex = 10;
    			this.btnFirst.Text = "| <";
    			this.btnFirst.Click += new System.EventHandler(this.btnFirst_Click);
    		
    			// Button: Previous
    			this.btnPrevious.Location = new System.Drawing.Point(144, 112);
    			this.btnPrevious.Name = "btnPrevious";
    			this.btnPrevious.Size = new System.Drawing.Size(48, 23);
    			this.btnPrevious.TabIndex = 11;
    			this.btnPrevious.Text = "<<";
    			this.btnPrevious.Click += new System.EventHandler(this.btnPrevious_Click);
    
    
    			// Button: Next
    			this.btnNext.Location = new System.Drawing.Point(232, 112);
    			this.btnNext.Size = new System.Drawing.Size(48, 23);
    			this.btnNext.TabIndex = 12;
    			this.btnNext.Text = ">>";
    			this.btnNext.Click += new System.EventHandler(this.btnNext_Click);
    
    			// Button: Last
    			this.btnLast.Location = new System.Drawing.Point(280, 112);
    			this.btnLast.Size = new System.Drawing.Size(48, 23);
    			this.btnLast.TabIndex = 13;
    			this.btnLast.Text = "> |";
    			this.btnLast.Click += new System.EventHandler(this.btnLast_Click);
    
    			// Form: Exercise
    			this.Controls.Add(this.btnClose);
    			this.Controls.Add(this.btnLast);
    			this.Controls.Add(this.btnNext);
    			this.Controls.Add(this.btnPrevious);
    			this.Controls.Add(this.btnFirst);
    			this.Controls.Add(this.txtUnitPrice);
    			this.Controls.Add(this.lblUnitPrice);
    			this.Controls.Add(this.txtSize);
    			this.Controls.Add(this.lblItemSize);
    			this.Controls.Add(this.txtDescription);
    			this.Controls.Add(this.lblDescription);
    			this.Controls.Add(this.txtItemNumber);
    			this.Controls.Add(this.lblItemNumber);
    
    			this.Size = new System.Drawing.Size(352, 184);
    			this.MaximizeBox = false;
    			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
    			this.Text = "Department Store";
    
    			this.Load += new System.EventHandler(this.Exercise_Load);
    
    		}
    
    		private void Exercise_Load(object sender, System.EventArgs e)
    		{
    			lstItemsInStore = Array.CreateInstance(typeof(CStoreItem), 6);
    
    			CStoreItem anItem = new CStoreItem();
    			anItem.ItemNumber = "724372";
    			anItem.ItemName   = "Women Coat";
    			anItem.Size       = "Large";
    			anItem.UnitPrice  = 225.55;
    			lstItemsInStore.SetValue(anItem, 0);
    
    			anItem = new StoreItem.CStoreItem();
    			anItem.ItemNumber = "624376";
    			anItem.ItemName   = "Men Jacket";
    			anItem.Size       = "Medium";
    			anItem.UnitPrice  = 175.75;
    			lstItemsInStore.SetValue(anItem, 1);
    
    			anItem = new StoreItem.CStoreItem();
    			anItem.ItemNumber = "274952";
    			anItem.ItemName   = "Teen Jeans";
    			anItem.Size       = "14";
    			anItem.UnitPrice  = 24.50;
    			lstItemsInStore.SetValue(anItem, 2);
    
    			anItem = new StoreItem.CStoreItem();
    			anItem.ItemNumber = "497852";
    			anItem.ItemName   = "Women Bathing Suit";
    			anItem.Size       = "Petite";
    			anItem.UnitPrice  = 34.65;
    			lstItemsInStore.SetValue(anItem, 3);
    
    			anItem = new StoreItem.CStoreItem();
    			anItem.ItemNumber = "749752";
    			anItem.ItemName   = "Children Playground Dress";
    			anItem.Size       = "12";
    			anItem.UnitPrice  = 75.05;
    			lstItemsInStore.SetValue(anItem, 4);
    
    			anItem = new StoreItem.CStoreItem();
    			anItem.ItemNumber = "394085";
    			anItem.ItemName   = "Boys Trousers";
    			anItem.Size       = "8";
    			anItem.UnitPrice  = 17.95;
    			lstItemsInStore.SetValue(anItem, 5);
    
    			CurrentPosition = 0;
    			btnFirst_Click(sender, e);
    		}
    
    		private void btnClose_Click(object sender, System.EventArgs e)
    		{
    			Close();
    		}
    
    		private void btnFirst_Click(object sender, System.EventArgs e)
    		{
    			CurrentPosition = 0;
    
    			try 
    			{
    				StoreItem.CStoreItem anItem = 
    					(CStoreItem)lstItemsInStore.GetValue(0);
    
    				this.txtItemNumber.Text  = anItem.ItemNumber;
    				this.txtDescription.Text = anItem.ItemName;
    				this.txtSize.Text        = anItem.Size;
    				this.txtUnitPrice.Text   = anItem.UnitPrice.ToString("C");
    			}
    			catch(IndexOutOfRangeException )
    			{
    				MessageBox.Show("Invalid Index: Contact the administrator and report this error");
    			}
    		}
    
    		private void btnPrevious_Click(object sender, System.EventArgs e)
    		{	
    			if( CurrentPosition == 0 )
    				return;
    			else
    			{
    				CurrentPosition--;
    
    				try 
    				{
    					StoreItem.CStoreItem anItem = 
    						(CStoreItem)lstItemsInStore.GetValue(CurrentPosition);
    
    					this.txtItemNumber.Text  = anItem.ItemNumber;
    					this.txtDescription.Text = anItem.ItemName;
    					this.txtSize.Text        = anItem.Size;
    					this.txtUnitPrice.Text   = anItem.UnitPrice.ToString("C");
    				}
    				catch(IndexOutOfRangeException )
    				{
    				MessageBox.Show("Invalid Index: Contact the administrator and report this error");
    				}
    			}
    		}
    
    		private void btnNext_Click(object sender, System.EventArgs e)
    		{
    			if( CurrentPosition == (lstItemsInStore.GetLength(0) - 1) )
    				return;
    			else
    			{
    				CurrentPosition++;
    
    				try 
    				{
    					StoreItem.CStoreItem anItem = 
    						(CStoreItem)lstItemsInStore.GetValue(CurrentPosition);
    
    					this.txtItemNumber.Text  = anItem.ItemNumber;
    					this.txtDescription.Text = anItem.ItemName;
    					this.txtSize.Text        = anItem.Size;
    					this.txtUnitPrice.Text   = anItem.UnitPrice.ToString("C");
    				}
    				catch(IndexOutOfRangeException )
    				{
    				MessageBox.Show("Invalid Index: Contact the administrator and report this error");
    				}
    			}
    		}
    
    		private void btnLast_Click(object sender, System.EventArgs e)
    		{
    			CurrentPosition = lstItemsInStore.GetLength(0) - 1;
    
    			try 
    			{
    				StoreItem.CStoreItem anItem = 
    					(CStoreItem)lstItemsInStore.GetValue(CurrentPosition);
    
    				this.txtItemNumber.Text  = anItem.ItemNumber;
    				this.txtDescription.Text = anItem.ItemName;
    				this.txtSize.Text        = anItem.Size;
    				this.txtUnitPrice.Text   = anItem.UnitPrice.ToString("C");
    			}
    			catch(IndexOutOfRangeException )
    			{
    				MessageBox.Show("Invalid Index: Contact the administrator and report this error");
    			}
    		}
    
    		static int Main() 
    		{
    			Application.Run(new Exercise());
    
    			return 0;
    		}
    	}
    }
  2. Save the file
  3. Return to the Command Prompt and compile  the program by typing
     
    csc /r:StoreItem.dll Exercise.cs
  4. Press Enter
  5. Execute the file by typing Exercise and pressing Enter
     
  6. Close the form

The Arrangement of the List

When a new item is added to the array, it assumes the last position. If you want, you can re-arrange the list in a consecutive order. If the list is a one-dimensional array made of strings, you can arrange it in alphabetical order. If it is made of numbers, you can order them in increment or decrement order. If the list is a two, three, or multi-dimensional array, you can arrange it based on a list-part of your choice. To support the ability to re-organize the list, the Array class is equipped with the Sort() method that is overloaded with as many versions as you can possibly need.

To arrange a single-dimensional array in a consecutive order, you can call the following version of the Array.Sort() method:

public static void Sort(Array array);

To reverse the sequence of items of a one-dimensional array, you can call the Array.Reverse() method. Its syntax is:

public static void Reverse(Array array);

 

Looking for an Item in an Array

When using a list, you may want to know whether a particular item exists in the list. There are usually two ways to perform this operation. You usually can use a for or a foreach statement to scan a list. With this approach, you navigate through the list by visiting the index of each item and checking the value of that index. Another solution consists of writing a function to perform the search. The Array class provides its own support of both solutions using various methods that can be used to perform this operation.

The Array.IndexOf() method scans a list by accessing the index of each item. This method is overloaded with three versions. To apply it on a single-dimensional array, use the following version:

public static int IndexOf(Array array, object value);

This method visits each member of the array, looking for the value. Once it finds value in the array, it stops and returns the index where the first occurrence of value was found. The IndexOf() method actually looks for the first occurrence of an item in an array. If you prefer to get the last occurrence of that item in the array, you can call the Array.LastIndexOf() method. It also is overloaded in three versions.

 


Home Copyright © 2004-2010 FunctionX, Inc.