Home

Introduction to Arrays

 

Objects as Arrays

 

Introduction

Like a primitive array, a class can be declared as an array member variable. There is nothing significant to do when declaring the field. Make sure you give it an appropriate name and add its square brackets. The approach is the same used for a primitive data type.

Practical LearningPractical Learning: Introducing Arrays and Classes

  1. Start Notepad and, in the empty file, type the following:
     
    using System;
    
    namespace Business
    {
    	interface IStockItem
    	{
    		string  PartNumber { get; set; }
    		string  PartName   { get; set; }
    		decimal UnitPrice  { get; set; }
    	}
    }
    
    namespace AutoParts
    {
    	public class Part : Business.IStockItem
    	{
    		private string    ID;
    		protected string  name;
    		protected decimal price;
    		private int       qty;
    
    		public string PartNumber
    		{
    			get	{ return ID;}
    			set	{ ID = value; }
    		}
    
    		public string PartName
    		{
    			get	{ return name; }
    			set	{ name = value; }  
    		}
    
    		public decimal UnitPrice
    		{
    			get	{ return (price < 0) ? 0.00M : price; }
    			set	{ price = value; }
    		}
    
    		public int Quantity
    		{
    			get { return (qty < 1) ? 1 : qty; }
    			set { qty = value; }
    		}
    
    		public Part()
    		{
    			this.ID = null;
    			this.name   = "Unknown";
    			this.price  = 0.00M;
    		}
    
    		public Part(string Nbr, string nm, decimal pr)
    		{
    			this.ID    = Nbr;
    			this.name  = nm;
    			this.price = pr;
    		}
    	}
    }
  2. On the main menu of Notepad, click File -> New
  3. When asked whether you want to save the changes, click Yes
  4. Inside of the CSharp Lessons folder, locate the Libraries1 folder and display it in the Save In combo box
  5. Change the Save As Type to All Files
  6. Set the file name to Parts.cs and click Save
  7. Open the Command Prompt and change to the above Libraries1 folder
  8. To create the DLL, type csc /target:library /out:PartCreator.dll Parts.cs and press Enter
  9. In the new empty file of Notepad, type the following:
     
    using System;
    
    namespace AutoParts
    {
    	struct PartsList
    	{
    		public static string[] ItemNumber = new string[]{
    			"GD646", "EU473", "AH325", "KS745", "KE374", "GD943",
    			"GH386", "WD394", "TR944", "GD844", "GD933", "GW478",
    			"LA943", "RU688", "PP797", "RA292", "AG778", "KQ820",
    			"GT722", "WA502", "AL848", "RU382", "HJ624", "RL555",
    			"PQ273", "ER162", "EY275", "LM357", "RU473", "QW374",
    			"QR374", "PQ902", "QT847", "PY784", "TQ483", "EQ173",
    			"UG376", "PI489", "BT389", "CQ274", "QX202", "GN780",
    			"XZ485", "BD199"};
    	
    		public static string[] Description = new string[]{
    			"Bearing Clutch Pilot  ", "Belt Accessory Drive  ",
    			"Break Drum            ", "Right Mirror          ",
    			"Break Shoe            ", "Signal Lamp Assembly  ",
    			"Bearing Input Shaft   ", "Brake Disc            ",
    			"Front Wheel Lug Nut   ", "Front Pump Gasket     ",
    			"Filter Steering       ", "Air Control Valve     ",
    			"Clutch Master Clndr   ", "Tie Rod               ",
    			"Ball Joint            ", "Drive Belt            ",
    			"Oil Filter            ", "Timing Belt           ",
    			"Intake Manifold Gask  ", "Spark Plug Seal       ",
    			"Air Filter            ", "Fuel Injector Clip    ",
    			"Brk Caliper w/o Pads  ", "Crankshaft Seal       ",
    			"Oil Pump              ", "Timing Belt Tensioner ",
    			"Camshaft Seal         ", "Valve Cover Gasket    ",
    			"Valve Stem Seal       ", "Starter               ",
    			"Radiator Cap          ", "Thermostat Gasket     ",
    			"Water Pump            ", "Spark Plug Platinum   ",
    			"Tie Rod Assembly      ", "Oil Pump              ",
    			"Piston Ring Set       ", "Distributor Cap       ",
    			"Oil Seal Front Pump   ", "Transmitter Filter Kit",
    			"Tail Lamp Assembly    ", "Bearing Wheel         ",
    			"Left Mirror           ", "Caliper Bolt/Pin      " };
    	
    	public static decimal[] Price = new decimal[]{
    	9.75M,   6.75M, 20.55M,   9.35M,  20.25M,  74.55M,  45.25M, 85.50M,
    	  1.75M,   0.72M,  1.55M,  35.25M, 124.55M,  32.55M,  25.75M, 10.65M,
    	  6.25M,  45.95M, 18.55M,   4.15M,  15.65M,  17.05M, 190.50M, 10.55M,
    	218.75M, 264.55M,  8.95M,  22.75M,   3.95M, 320.65M,  12.75M,  4.20M,
    	 12.95M, 145.85M,  3.95M, 155.75M, 218.75M, 275.55M,   7.05M,  9.25M,
    			  5.05M,  40.15M,  7.25M,   3.55M };
    	}
    }
  10. On the main menu of Notepad, click File -> New
  11. When asked whether you want to save the changes, click Yes
  12. Inside of the CSharp Lessons folder, create a folder named AutoParts1 and display it in the Save In combo box
  13. Change the Save As Type to All Files
  14. Set the file name to PartsList.cs and press Enter
  15. In the new and empty file of Notepad, type the following:
     
    using System;
    
    namespace AutoParts
    {
    	// This class is used to create and manage a list of auto parts
    	// The list will be created as array-based
    	class ListOfParts
    	{
    		// Because we are going to create an array-based list, 
    		// we will use this constant as its dimension
    		const int MaxItems = 100;
    		
    	// This will help us keep track on the number of items in the list
    		int SizeOfList;
    
    	// This method is used to add a new item to the list of auto parts
    		public void Add(Part P)
    		{
    			// Increase the count of items of the list
    			SizeOfList++;
    		}
    
    		// This method simply returns an item from the array,
    		// using a specified index
    		public Part Retrieve(int n)
    		{
    		
    		}
    
    	// This method returns the current number of items in the list
    		public int Count()
    		{
    			return SizeOfList;
    		}
    
    		// Default Constructor: Used to initialize an object
    		public ListOfParts()
    		{
    	// When this class is primarily accessed, we want to indicate that
    			// its list is empty
    			SizeOfList = 0;
    		}
    
    	}
    }
  16. Save the new file as ListCreator.cs in the same AutoParts1 folder
  17. Open Windows Explorer or My Computer
  18. From the CSharp Lessons\Libraries1 folder, copy PartCreator.dll and paste it in the AutoParts1 folder
  19. Open a new instance of Notepad and type the following in it:
     
    using System;
    
    namespace AutoParts
    {
    	class OrderProcessing
    	{
    	}
    
    	class Exercise
    	{
    		static void Main()
    		{
    		}
    	}
    }
  20. Save the new file as Exercise.cs in the same AutoParts1 folder

 

A Class as an Array Field

To declare a class as a member array of another class, you use the same technique as for primitive types. This means that you can declare the array somewhere in the body of the class. Before the variable can be used, make sure you have allocated memory for it, which is done using the new operator. In C# (unlike C++), you can allocate memory either when declaring the array or in a method that would precede its use. A constructor is a prime candidate for this operation.

After allocating memory for the variable, you can use as you see fit. If its values would only be made available to the users, you should make sure the variable has been initialized prior to being used. You can also initialize an array using values requested from the user. You can easily apply the techniques we have used so far on arrays.

Practical LearningPractical Learning: Declaring a Class as an Array Field

  1. To declare a class as an array member variable and apply what we have learned so far, change the ListCreator.cs file as follows:
     
    using System;
    
    namespace AutoParts
    {
    	// This class is used to create and manage a list of auto parts
    	// The list will be created as array-based
    	class ListOfParts
    	{
    		// Because we are going to create an array-based list, 
    		// we will use this constant as its dimension
    		const int MaxItems = 100;
    		// An object declared as array
    		Part[] Item = new Part[MaxItems];
    		// This will help us keep track on the number of items in the list
    		int SizeOfList;
    
    		// This method is used to add a new item to the list of auto parts
    		public void Add(Part P)
    		{
    			// Before adding a new item, first make sure that we still have room
    			if( SizeOfList < MaxItems )
    			{
    				// If we still have room, add the new item to the array
    				Item[SizeOfList] = P;
    				// Increase the count of items of the list
    				SizeOfList++;
    			}
    		}
    
    		// This method simply return an item from the array, using a specified index
    		public Part Retrieve(int n)
    		{
    			return Item[n];
    		}
    
    		// This method returns the current number of items in the list
    		public int Count()
    		{
    			return SizeOfList;
    		}
    
    		// Default Constructor: Used to initialize an object
    		public ListOfParts()
    		{
    			// When this class is primarily accessed, we want to indicate that
    			// its list is empty
    			SizeOfList = 0;
    		}
    
    	}
    }
  2. Save the file
  3. Access the Exercise.cs file and change it as follows:
     
    using System;
    
    namespace AutoParts
    {
    	// This class is used to perform a customer's order
    	class OrderProcessing
    	{
    		static void Main()
    		{
    			ListOfParts lstParts = new ListOfParts();
    
    			ProcessAnItem(lstParts);
    			Console.WriteLine();
    			DisplayReceipt(lstParts);
    		}
    		
    		// This method is used to request a part number from the user
    		// Check if that part number exists in the database
    		// If it does, the method adds that part to the list
    		static void ProcessAnItem(ListOfParts LOP)
    		{
    			Part AnItem;
    			string PartID;
    			int    Qty;
        
    			// Ask the user to enter a part number
    			do 
    			{
    				Console.Write("Enter the part number (q to stop): ");
    				PartID = Console.ReadLine();
    
    				// Scan the list
    				for(int i = 0; i < PartsList.Description.Length; i++)
    				{
    					AnItem = new Part();
    					
    					// If the part number exists in our database	
    					if( PartID == PartsList.ItemNumber[i] )
    					{
    						// Create a Part object from it
    						AnItem.PartNumber = PartsList.ItemNumber[i];
    						AnItem.PartName   = PartsList.Description[i];
    						AnItem.UnitPrice  = PartsList.Price[i];
    						
    						// Request the quantity from the user
    						try 
    						{
    							Console.Write("How many? ");
    							Qty = int.Parse(Console.ReadLine());
    							AnItem.Quantity = Qty;
    						}
    						catch(FormatException)
    						{
    						Console.WriteLine("Invalid Quantity!!!");
    						}
    
    					// Once the part has been "built", add it to the order
    						LOP.Add(AnItem);
    						// Check no further
    						break;
    					}
    				}
    			} while( PartID != "q" && PartID != "Q" );
    		}
    
    		// This method is used to display a receipt
    		// It uses a list, Receipt, passed as argument
    		// It also calculates the price of each item and the total price of the order
    		// They are also part of the receipt
    		static void DisplayReceipt(ListOfParts Receipt)
    		{
    			decimal SubTotal   = 0.00M,
    				TotalOrder = 0.00M;
    			
    		Console.WriteLine("========================================================");
    		Console.WriteLine("    =-= Four-Corner Auto-Parts =-=");
    		Console.WriteLine("------+---+-------------------------+-------+-----------");
    		Console.WriteLine("Part#  Qty  Description               Price   SubTotal");
    		Console.WriteLine("------+---+-------------------------+-------+-----------");
        
    			for(int i = 0; i < Receipt.Count(); i++)
    			{
    				//TPart Item = Receipt.Retrieve(i);
    				SubTotal = Receipt.Retrieve(i).UnitPrice *
    					  Receipt.Retrieve(i).Quantity;
    
    				TotalOrder += SubTotal;
    
    				Console.WriteLine("{0}   {1}   {2}    {3,6}    {4,6}",
    					Receipt.Retrieve(i).PartNumber,
    					Receipt.Retrieve(i).Quantity,
    					Receipt.Retrieve(i).PartName,
    					Receipt.Retrieve(i).UnitPrice,
    					SubTotal);
    			}                                      
     
    		Console.WriteLine("------+---+-------------------------+-------+-----------");
    			Console.WriteLine("Total Order: {0:C}", TotalOrder);
    		Console.WriteLine("========================================================\n");
    		}
    	}
    }
  4. Save the file
  5. Access the Command Prompt and change to the above AutoParts1 folder
  6. To compile it, type csc /reference:PartCreator.dll /out:"Four-Corner Auto-Parts".exe ListCreator.cs PartsList.cs Exercise.cs and press Enter
  7. To execute it, type "Four-Corner Auto-Parts" and press Enter. Here is an example of processing an order:
     
    C:\>CD CSharp Lessons\Libraries1
    
    C:\CSharp Lessons\Libraries1>csc /target:library /out:PartCreator.dll Parts.cs
    Microsoft (R) Visual C# .NET Compiler version 7.10.3052.4
    for Microsoft (R) .NET Framework version 1.1.4322
    Copyright (C) Microsoft Corporation 2001-2002. All rights reserved.
    
    
    C:\CSharp Lessons\Libraries1>CD\
    
    C:\>CD CSharp Lessons\AutoParts1
    
    C:\CSharp Lessons\AutoParts1>csc /reference:PartCreator.dll /out:"Four-Corner Au
    to-Parts".exe ListCreator.cs PartsList.cs Exercise.cs
    Microsoft (R) Visual C# .NET Compiler version 7.10.3052.4
    for Microsoft (R) .NET Framework version 1.1.4322
    Copyright (C) Microsoft Corporation 2001-2002. All rights reserved.
    
    
    C:\CSharp Lessons\AutoParts1>"Four-Corner Auto-Parts"
    Enter the part number (q to stop): LA943
    How many? 1
    Enter the part number (q to stop): TR944
    How many? 2
    Enter the part number (q to stop): EQ173
    How many? 1
    Enter the part number (q to stop): QT847
    How many? 1
    Enter the part number (q to stop): q
    
    ========================================================
        =-= Four-Corner Auto-Parts =-=
    ------+---+-------------------------+-------+-----------
    Part#  Qty  Description               Price   SubTotal
    ------+---+-------------------------+-------+-----------
    LA943   1   Clutch Master Clndr       124.55    124.55
    TR944   2   Front Wheel Lug Nut         1.75      3.50
    EQ173   1   Oil Pump                  155.75    155.75
    QT847   1   Water Pump                 12.95     12.95
    ------+---+-------------------------+-------+-----------
                    Total Order: $296.75
    ========================================================
  8. Return to Notepad
 

Introduction to Collections

Like an array, a collection is a series of items of the same type. The problem with an array is that you must know in advance the number of items that will make up the list. There are cases you don't know, you can't know, or you can't predict the number of items of the list. The solution is to create a linked list. A linked list is a list in which you don't specify the maximum number of items but you allow the user of the list to add, locate, or remove items at will. Traditionally, it has never been easy to create a linked list, especially for beginning programmers. Aware of this, many programming languages ship with one or more libraries that can be used directly to create a list of almost any kind.

The Microsoft .NET Framework provides various classes that can be used to create different types of lists. Most of the classes are easy to use once you get used to them. The idea is to know what classes are available, what a class does, and what class to use for a particular assignment.

 


Home Copyright © 2004-2012, FunctionX