Home

Arrays and Classes

 

Primitive Arrays as Fields

 

Introduction

As we have used so far, an array is primarily a variable. As such, it can be declared as a field. To create a field as an array, you can declare it like a normal array in the body of the class. Here is an example:

using System;

namespace Arithmetic
{
	class NumberCrunching
	{
		double[] number;
	}
}

Practical LearningPractical Learning: Introducing Primitive Arrays as Fields of a Class

  1. Start Notepad and, in the empty file, type the following:
     
    using System;
    
    namespace VendingMachine
    {
        // This class is used to create an ice cream
        // And to process an order
        sealed class IceCream
        {
        }
    }
  2. Save the file in a new folder named IceCream3
  3. Save the file itself as IceCream.cs in the IceCream3 folder
  4. Start a new instance of Notepad and type the following:
     
    using System;
    
    // This is the main class used to manage the application
    class Exercise
    {
        static int Main()
        {
           return 0;
        }
    }
  5. Save the file as Exercise.cs in a the above IceCream3 folder
  6. To declare fields as arrays, access the IceCream.cs file and change it as follows:
     
    using System;
    
    namespace VendingMachine
    {
        // This class is used to create an ice cream
        // And to process an order
        sealed class IceCream
        {
            // These arrays are used to build the components of various ice creams
            private string[] Flavor;	
            private string[] Container;
            private string[] Ingredient;
        }
    }
  7. Save the file

A Primitive Array as a Field

Like any field, when an array has been declared as a member variable, it is made available to all the other members of the same class. You can use this feature to initialize the array in one method and let other methods use the initialized variable. This also means that you don't have to pass the array as argument nor do you have to explicitly return it from a method.

After or when declaring an array, you must make sure you allocate memory for it prior to using. Unlike C++, you can allocate memory for an array when declaring it. Here is an example:

using System;

namespace Arithmetic
{
	class NumberCrunching
	{
		double[] number = new double[5];
	}
}

You can also allocate memory for an array field in a constructor of the class. Here is an example:

using System;

namespace Arithmetic
{
	class NumberCrunching
	{
		double[] Number;
		
		public NumberCrunching()
		{
			Number = new double[5];
		}
	}
}

If you plan to use the array as soon as the program is running, you can initialize it using a constructor or a method that you know would be before the array can be used. Here is an example:

using System;

namespace Arithmetic
{
	class NumberCrunching
	{
		double[] Number = new double[5];
		
		public NumberCrunching()
		{
			Number[0] = 12.44;
			Number[1] = 525.38;
			Number[2] = 6.28;
			Number[3] = 2448.32;
			Number[4] = 632.04;
		}
	}
}

 

 
 

Practical LearningPractical Learning: Creating Fields as Primitive Arrays in a Class

  1. To initialize the arrays of the class, change the IceCream.cs file as follows:
     
    using System;
    
    namespace VendingMachine
    {
        // This class is used to create an ice cream
        // And to process an order
        sealed class IceCream
        {
            // These arrays are used to build the components of various ice creams
            // In C#, we can allocate an array's memory in the body of the class
            private string[] Flavor = new string[10];	
            private string[] Container;
            private string[] Ingredient;
    
            // This default constructor is the best place for us to initialize the array
            public IceCream()
            {
                Flavor[0] = "Vanilla";
    	   Flavor[1] = "Cream of Cocoa";
    	   Flavor[2] = "Chocolate Chip";
    	   Flavor[3] = "Organic Strawberry";
                Flavor[4] = "Butter Pecan";
    	   Flavor[5] = "Cherry Coke";
    	   Flavor[6] = "Chocolate Brownies";
    	   Flavor[7] = "Caramel Au Lait";
    	   Flavor[8] = "Chunky Butter";
    	   Flavor[9] = "Chocolate Cookie";
    
                Ingredient = new string[4];
    	   Ingredient[0] = "No Ingredient";
    	   Ingredient[1] = "Peanuts";
    	   Ingredient[2] = "M & M";
    	   Ingredient[3] = "Cookies";
    
                Container  = new string[3];
    	   Container[0] = "Cone";
    	   Container[1] = "Cup";
    	   Container[2] = "Bowl";
            }
        }
    }
  2. Save the file

Use of a Primitive Array as a Field

Remember that, after an array is made a field, it can be used by any other member of the same class. Based on this, you can use a member of the same class to request values that would initialize it. You can also use another method to explore the array. Here is an example:

using System;

namespace Arithmetic
{
	class NumberCrunching
	{
		double[] Number = new double[5];
		
		public NumberCrunching()
		{
			Number[0] = 12.44;
			Number[1] = 525.38;
			Number[2] = 6.28;
			Number[3] = 2448.32;
			Number[4] = 632.04;
		}

		public void DisplayNumber()
		{
			for (int i = 0; i < 5; i++)
				Console.WriteLine("Number {0}: {1}", i, Number[i]);
		}
	}

	class Program
	{
		static void Main()
		{
			NumberCrunching lstNumber = new NumberCrunching();

			lstNumber.DisplayNumber();
		}
	}
}

Practical LearningPractical Learning: Using Primitive Arrays in a Class

  1. To use the arrays throughout the class, change the IceCream.cs file as follows:
     
    using System;
    
    namespace VendingMachine
    {
        // This class is used to create and manage an ice cream
        // and to process an order
        sealed class IceCream
        {
             // This is the base price of an ice cream
    	// Optional values may be added to it
    	public const decimal BasePrice = 1.55M;
    
             // These arrays are used to build the components of various ice creams
             // In C#, we can allocate an array's memory in the body of the class
             private string[] Flavor = new string[10];	
             private string[] Container;
             private string[] Ingredient;
    
    	// Additional factor used to process an ice cream order
    	private int Scoops;
    	private decimal TotalPrice;
    
            // This default constructor is the best place for us to initialize the array
            public IceCream()
            {
                 Flavor[0] = "Vanilla";
    	    Flavor[1] = "Cream of Cocoa";
    	    Flavor[2] = "Chocolate Chip";
    	    Flavor[3] = "Organic Strawberry";
    	    Flavor[4] = "Butter Pecan";
    	    Flavor[5] = "Cherry Coke";
    	    Flavor[6] = "Chocolate Brownies";
    	    Flavor[7] = "Caramel Au Lait";
    	    Flavor[8] = "Chunky Butter";
    	    Flavor[9] = "Chocolate Cookie";
    
                 Ingredient = new string[4];
    	    Ingredient[0] = "No Ingredient";
    	    Ingredient[1] = "Peanuts";
    	    Ingredient[2] = "M & M";
    	    Ingredient[3] = "Cookies";
    
    	    Container  = new string[3];
                 Container[0] = "Cone";
    	    Container[1] = "Cup";
    	    Container[2] = "Bowl";
            }
    
    	// This method requests a flavor from the user and returns the choice
    	public int ChooseFlavor()
    	{
    	    int Choice = 0;
    
    	    // Make sure the user selects a valid number that represents a flavor...
                do 
    	    {
    		// In case the user types a symbol that is not a number
    		try 
    		{
    	            Console.WriteLine("What type of flavor do you want?");
    		    for(int i = 0; i < Flavor.Length; i++)
                    		Console.WriteLine("{0} - {1}", i+1, Flavor[i]);
    	            Console.Write("Your Choice? " );
    		    Choice = int.Parse(Console.ReadLine());
    		}
    		catch(FormatException)	// display an appropriate message
    		{
    		    Console.WriteLine("You must enter a valid number and no other character!");
    		}
    		
    		// If the user typed an invalid number out of the allowed range
    		// let him or her know and provide another chance
    		if( Choice < 1 || Choice > Flavor.Length )
    		    Console.WriteLine("Invalid Choice - Try Again!\n");
    	    } while( Choice < 1 || Choice > Flavor.Length );
    
    	    // Return the numeric choice that the user made
                return Choice;
    	}
    
    	// This method allows the user to select a container
    	public int ChooseContainer()
    	{
                int Choice = 0;
    
    	    // Make sure the user selects a valid number that represents a container
                do 
    	    {
    		// If the user types a symbol that is not a number
    		try 
    		{
    	            Console.WriteLine("What type of container do you want?");
    		    for(int i = 0; i < Container.Length; i++)
    		 	Console.WriteLine("{0} - {1}", i+1, Container[i]);
    		    Console.Write("Your Choice? ");
    		    Choice = int.Parse(Console.ReadLine());
    		}
    		catch(FormatException)	// display an appropriate message
    		{
    		    Console.WriteLine("You must enter a valid number and no other character!");
    		}
    			
    		// If the user typed an invalid number out of the allowed range
    		// let him or her know and provide another chance
    		if( Choice < 1 || Choice > Container.Length )
    	            Console.WriteLine("Invalid Choice - Try Again!");
    	    } while( Choice < 1 || Choice > Container.Length );
    
    	    // Return the numeric choice that the user made
                return Choice;
    	}
    
    	public int ChooseIngredient()
    	{
                int Choice = 0;
    
                do 
    	    {
    		try 
    		{
    	            Console.WriteLine("Do you want an ingredient or not");
    		    for(int i = 0; i < Ingredient.Length; i++)
    			Console.WriteLine("{0} - {1}", i+1, Ingredient[i]);
    		    Console.Write("Your Choice? ");
    		    Choice = int.Parse(Console.ReadLine());
    		}
    		catch(FormatException)
    		{
    		    Console.WriteLine("You must enter a valid number and no other character!");
    		}
    
    		if( Choice < 1 || Choice > Ingredient.Length )
                        Console.WriteLine("Invalid Choice - Try Again!");
    	    } while( Choice < 1 || Choice > Ingredient.Length );
    		
    	    return Choice;
    	}
    
    	public void SpecifyNumberOfScoops()
    	{
                do
    	    {
    		try 
    		{
    	            Console.Write("How many scoops(1, 2, or 3)? ");
    		    Scoops = int.Parse(Console.ReadLine());
    		}
    		catch(FormatException)
    		{
    		    Console.WriteLine("You must enter a valid number and no other character!");
    		}
    
    		if( Scoops < 1 || Scoops > 3 )
                        Console.WriteLine("Invalid Choice - Try Again!");
    	    } while( Scoops < 1 || Scoops > 3 );
    	}
    
    	// This method is used to process a customer order
    	// It uses the values of the above methods
    	public void ProcessAnOrder()
    	{
                 int ChoiceFlavor;
    	    int ChoiceContainer;
    	    int ChoiceIngredient;
                 decimal PriceIngredient, PriceScoop;
    
    	    // Let the user know that this is a vending machine
                 Console.WriteLine("Ice Cream Vending Machine");
    
    	    // Let the user select the components of the ice cream
                 ChoiceFlavor = ChooseFlavor();
    	    ChoiceContainer = ChooseContainer();
    	    ChoiceIngredient = ChooseIngredient();
    	    SpecifyNumberOfScoops();
    
    	    // If the user selects an ingredient instead of "No Ingredient",
    	    // add $0.50 to the order
                if( ChoiceIngredient == 2 || ChoiceIngredient == 3 || ChoiceIngredient == 4 )
    		PriceIngredient = 0.50M;
    	    else
    		PriceIngredient = 0.00M;
    
    	    // Instead of multiplying a number scoops to a value,
    	    // We will use an incremental value depending on the number of scoops
                if( Scoops == 1 )
    		PriceScoop = 0.65M;
                else if( Scoops == 2 )
    		PriceScoop = 1.05M;
                else
    		PriceScoop = 1.55M;
    
    	    // Calculate the total price of the ice cream
                TotalPrice = BasePrice + PriceScoop + PriceIngredient;
    
    	    // Create the ice cream...
    
    	    // And display a receipt to the user
                DisplayReceipt(ref ChoiceFlavor, ref ChoiceContainer, ref ChoiceIngredient);
    	}
    
    	// This method is used to display a receipt to the user
    	public void DisplayReceipt(ref int Flv, ref int Cnt, ref int Igr)
    	{
                 Console.WriteLine("\nIce Cream Order");
                 Console.WriteLine("Flavor:      {0}", Flavor[Flv-1]);
                 Console.WriteLine("Container:   {0}", Container[Cnt-1]);
    	    Console.WriteLine("Ingredient:  {0}", Ingredient[Igr-1]);
    	    Console.WriteLine("Scoops:      {0}", Scoops);
    	    Console.WriteLine("Total Price: {0:C}\n", TotalPrice);
    	}
        }
    }
  2. Save the IceCream.cs file
  3. Access the Exercise.cs file and change it as follows:
     
    using System;
    
    namespace VendingMachine
    {
        // This is the main class used to manage the application
        class Exercise
        {
            static int Main()
            {
    	    VendingMachine.IceCream IS = new VendingMachine.IceCream();
    
    	    IS.ProcessAnOrder();
    	    return 0;
            }
        }
    }
  4. Save the Exercise.cs file
  5. Open the Command Prompt and change to the directory that contains the above Exercise.cs file
  6. To compile it, type csc /out:"Ice Cream Vending Machine".exe IceCream.cs Exercise.cs and press Enter
  7. To execute it, type "Ice Cream Vending Machine" and press Enter. Here is an example:
     
    C:\>CD CSharp Lessons\IceCream3
    
    C:\CSharp Lessons\IceCream3>csc /out:"Ice Cream Vending Machine".exe IceCream
    .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\IceCream3>"Ice Cream Vending Machine"
    Ice Cream Vending Machine
    What type of flavor do you want?
    1 - Vanilla
    2 - Cream of Cocoa
    3 - Chocolate Chip
    4 - Organic Strawberry
    5 - Butter Pecan
    6 - Cherry Coke
    7 - Chocolate Brownies
    8 - Caramel Au Lait
    9 - Chunky Butter
    10 - Chocolate Cookie
    Your Choice? 8
    What type of container do you want?
    1 - Cone
    2 - Cup
    3 - Bowl
    Your Choice? 2
    Do you want an ingredient or not
    1 - No Ingredient
    2 - Peanuts
    3 - M & M
    4 - Cookies
    Your Choice? 6
    Invalid Choice - Try Again!
    Do you want an ingredient or not
    1 - No Ingredient
    2 - Peanuts
    3 - M & M
    4 - Cookies
    Your Choice? g
    You must enter a valid number and no other character!
    Invalid Choice - Try Again!
    Do you want an ingredient or not
    1 - No Ingredient
    2 - Peanuts
    3 - M & M
    4 - Cookies
    Your Choice? 2
    How many scoops(1, 2, or 3)? 2
    
    Ice Cream Order
    Flavor:      Caramel Au Lait
    Container:   Cup
    Ingredient:  Peanuts
    Scoops:      2
    Total Price: $3.10
    
    
    C:\CSharp Lessons\IceCream3>
  8. Return to Notepad

foreach Item in the Series

In the previous lessons, we used the traditional techniques of locating each item in an array. Here is an example:

class Exercise
{
    static int Main()
    {
	string[] EmployeeName = new string[4];

	EmployeeName[0] = "Joan Fuller";
	EmployeeName[1] = "Barbara Boxen";
	EmployeeName[2] = "Paul Kumar";
	EmployeeName[3] = "Bertrand Entire";

	Console.WriteLine("Employees Records");
	Console.WriteLine("Employee 1: {0}", EmployeeName[0]);
	Console.WriteLine("Employee 2: {0}", EmployeeName[1]);
	Console.WriteLine("Employee 3: {0}", EmployeeName[2]);
	Console.WriteLine("Employee 4: {0}", EmployeeName[3]);

         return 0;
    }
}

To scan a list, the C# language provides two keyword, foreach and in, with the following syntax:

foreach (type identifier in expression) statement

The foreach and the in keywords are required.

The first factor of this syntax, type, must be a data type (int, short, Byte, Double, etc) or the name of a class that either exists in the language or that you have created.

The identifier factor is a name you specify to represent an item of the collection.

The expression factor is the name of the array or collection.

The statement to execute while the list is scanned is the statement factor in our syntax.

Here is an example:

class Exercise
{
    static int Main()
    {
	string[] EmployeeName = new string[4];

	EmployeeName[0] = "Joan Fuller";
	EmployeeName[1] = "Barbara Boxen";
	EmployeeName[2] = "Paul Kumar";
	EmployeeName[3] = "Bertrand Entire";

	Console.WriteLine("Employees Records");
	foreach(string strName in EmployeeName)
	    Console.WriteLine("Employee Name: {0}", strName);

        return 0;
    }
}

This would produce:

Employees Records
Employee Name: Joan Fuller
Employee Name: Barbara Boxen
Employee Name: Paul Kumar
Employee Name: Bertrand Entire

Practical LearningPractical Learning: Using foreach

  1. To use a foreach statement, change the IceCream.cs file as follows:
     
    using System;
    
    namespace VendingMachine
    {
        // This class is used to create and manage an ice cream
        // and to process an order
        sealed class IceCream
        {
            . . . No Change
    
            // This default constructor is the best place for us to initialize the array
            public IceCream()
            {
                . . . No Change
            }
    
    	// This method requests a flavor from the user and returns the choice
    	public int ChooseFlavor()
    	{
    	    int Choice = 0;
    
    	    // Make sure the user selects a valid number that represents a flavor...
                do 
    	    {
    		// In case the user types a symbol that is not a number
    		try 
    		{
    		    int i = 1;
    
    	             Console.WriteLine("What type of flavor do you want?");
    		    foreach(string Flv in Flavor)
                    	        Console.WriteLine("{0} - {1}", i++, Flv);
    	             Console.Write("Your Choice? " );
    		    Choice = int.Parse(Console.ReadLine());
    		}
    		catch(FormatException)	// display an appropriate message
    		{
    		    Console.WriteLine("You must enter a valid number and no other character!");
    		}
    		
    		// If the user typed an invalid number out of the allowed range
    		// let him or her know and provide another chance
    		if( Choice < 1 || Choice > Flavor.Length )
    		    Console.WriteLine("Invalid Choice - Try Again!\n");
    	    } while( Choice < 1 || Choice > Flavor.Length );
    
    	    // Return the numeric choice that the user made
                return Choice;
    	}
    
    	// This method allows the user to select a container
    	public int ChooseContainer()
    	{
                int Choice = 0;
    
    	    // Make sure the user selects a valid number that represents a container
                do 
    	    {
    		// If the user types a symbol that is not a number
    		try 
    		{
    		    int i = 1;
    
    	             Console.WriteLine("What type of container do you want?");
    		    foreach(string Cnt in Container)
    		 	Console.WriteLine("{0} - {1}", i++, Cnt);
    		    Console.Write("Your Choice? ");
    		    Choice = int.Parse(Console.ReadLine());
    		}
    		catch(FormatException)	// display an appropriate message
    		{
    		    Console.WriteLine("You must enter a valid number and no other character!");
    		}
    			
    		// If the user typed an invalid number out of the allowed range
    		// let him or her know and provide another chance
    		if( Choice < 1 || Choice > Container.Length )
    	            Console.WriteLine("Invalid Choice - Try Again!");
    	    } while( Choice < 1 || Choice > Container.Length );
    
    	    // Return the numeric choice that the user made
                return Choice;
    	}
    
    	public int ChooseIngredient()
    	{
                int Choice = 0;
    
                do 
    	    {
    		try 
    		{
    		    int i = 1;
    
    	             Console.WriteLine("Do you want an ingredient or not");
    		    foreach(string Ingrd in Ingredient)
    			Console.WriteLine("{0} - {1}", i++, Ingrd);
    		    Console.Write("Your Choice? ");
    		    Choice = int.Parse(Console.ReadLine());
    		}
    		catch(FormatException)
    		{
    		    Console.WriteLine("You must enter a valid number and no other character!");
    		}
    
    		if( Choice < 1 || Choice > Ingredient.Length )
                        Console.WriteLine("Invalid Choice - Try Again!");
    	    } while( Choice < 1 || Choice > Ingredient.Length );
    		
    	    return Choice;
    	}
    
    	public void SpecifyNumberOfScoops()
    	{
                . . . No Change
    	}
    
    	// This method is used to process a customer order
    	// It uses the values of the above methods
    	public void ProcessAnOrder()
    	{
                
    	    . . . No Change
    
    	}
    
    	// This method is used to display a receipt to the user
    	public void DisplayReceipt(ref int Flv, ref int Cnt, ref int Igr)
    	{
                . . . No Change
    	}
        }
    }
  2. Save, compile, and execute the application. Here is an example:
     
    C:\CSharp Lessons\IceCream3>csc /out:"Ice Cream Vending Machine".exe IceCream
    .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\IceCream3>"Ice Cream Vending Machine"
    Ice Cream Vending Machine
    What type of flavor do you want?
    1 - Vanilla
    2 - Cream of Cocoa
    3 - Chocolate Chip
    4 - Organic Strawberry
    5 - Butter Pecan
    6 - Cherry Coke
    7 - Chocolate Brownies
    8 - Caramel Au Lait
    9 - Chunky Butter
    10 - Chocolate Cookie
    Your Choice? 10
    What type of container do you want?
    1 - Cone
    2 - Cup
    3 - Bowl
    Your Choice? 4
    Invalid Choice - Try Again!
    What type of container do you want?
    1 - Cone
    2 - Cup
    3 - Bowl
    Your Choice? 3
    Do you want an ingredient or not
    1 - No Ingredient
    2 - Peanuts
    3 - M & M
    4 - Cookies
    Your Choice? 8
    Invalid Choice - Try Again!
    Do you want an ingredient or not
    1 - No Ingredient
    2 - Peanuts
    3 - M & M
    4 - Cookies
    Your Choice? 4
    How many scoops(1, 2, or 3)? 3
    
    Ice Cream Order
    Flavor:      Chocolate Cookie
    Container:   Bowl
    Ingredient:  Cookies
    Scoops:      3
    Total Price: $3.60
    
    
    C:\CSharp Lessons\IceCream3>
  3. Return to Notepad

Arrays of Objects and the Main Class

 

Introduction

Like a primitive array, a class can be declared and used as an array in the main class. 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 Array Objects in the Main Class

  1. Start a new file in Notepad and type the following:
     
    using System;
    
    namespace Business
    {
    	interface IStoreInventory
    	{
    		long ItemNumber { get; set; }
    		string ItemName  { get; set; }
    		decimal UnitPrice  { get; set; }
    	}
    }
    
    namespace DepartmentStore
    {
    	public sealed class StoreItem : Business.IStoreInventory
    	{
    		private long    itemNo;
    		private string  name;
    		private decimal price;
    
    		public long ItemNumber
    		{
    			get	{ return itemNo;}
    			set	{ itemNo = value; }
    		}
    
    		public string ItemName
    		{
    			get	{ return name; }
    			set	{ name = value; }  
    		}
    
    		public decimal UnitPrice
    		{
    			get	{ return (price < 0 ) ? 0.00M : price;}
    			set	{ price = value; }
    		}
    
    		public StoreItem()
    		{
    			this.itemNo = 0;
    			this.name   = "Unknown";
    			this.price  = 0.00M;
    		}
    
    		public StoreItem(long Nbr, string nm, decimal pr)
    		{
    			this.itemNo = 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, create a folder named Libraries1 and display it in the Save In combo box
  5. Change the Save As Type to All Files
  6. Set the file name to StoreItem.cs and click Save
  7. Access the Command Prompt and change to the above Libraries1 folder
  8. To create the DLL, type csc /target:library /out:ItemManager.dll StoreItem.cs and press Enter
  9. Return to Notepad
  10. In the new empty file of Notepad, type the following:
     
    using System;
    
    namespace DepartmentStore
    {
    	public class OrderProcessing
    	{
    		static void Main()
    		{
    			StoreItem dptStore = new StoreItem();
    
    			Console.WriteLine("Department Store");
    			Console.WriteLine("Item #:      {0}",   dptStore.ItemNumber);
    			Console.WriteLine("Description: {0}",   dptStore.ItemName);
    			Console.WriteLine("Unit Price:  {0:C}", dptStore.UnitPrice);
    
    			Console.WriteLine();
    		}
    	}
    }
  11. Save the file in a new folder named DeptStore6
  12. Save the file itself as Exercise.cs in the DeptStore6 folder
  13. Open Windows Explorer or My Computer
  14. From the CSharp Lessons\Libraries1 folder, copy ItemManager.dll and paste it in the DeptStore6 folder
  15. Access the Command Prompt and change to the DeptStore6 folder
  16. To compile the application, csc /reference:ItemManager.dll Exercise.cs and press Enter
  17. To execute the application, type Exercise. and press Enter. This would produce:
     
    C:\CSharp Lessons\IceCream3>cd\
    
    C:\>CD CSharp Lessons\Libraries1
    
    C:\CSharp Lessons\Libraries1>csc /target:library /out:ItemManager.dll StoreItem.
    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\DeptStore6
    
    C:\CSharp Lessons\DeptStore6>csc /reference:ItemManager.dll 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\DeptStore6>Exercise
    Department Store
    Item #:      0
    Description: Unknown
    Unit Price:  $0.00
    
    
    C:\CSharp Lessons\DeptStore6>
  18. Return to Notepad

A Class as an Array Member Variable

To use a class as an array member variable of the main class, declare the array as we have used them so far but make it static. For example, imagine you have created a class as follows:

using System;

namespace CSharpLessons
{
	public class Square
	{
		private double _side;

		public Square() { _side = 0; }
		public double Side
		{
			get { return _side; }
			set { _side = value; }
		}
		public Double Perimeter
		{
			get { return _side * 4; }
		}
		public double Area
		{
			get { return _side * _side; }
		}
	}
}

Here is how you can declare an array variable from the above class:

using System;

namespace CSharpLessons
{
	class Exercise
	{
		static Square[] Sq = new Square[2];

		static void Main(string[] args)
		{
		}
	}
}

After declaring the array, you can initialize it using the Main() function. You should first allocate memory using the new operator for each member of the array. Each member of the array is accessed using its index. Once the array exists, you can access each member of the class indirectly from the index of the variable. Here is an example:

using System;

namespace CSharpLessons
{
	class Exercise
	{
		static Square[] Sq = new Square[2];

		static void Main(string[] args)
		{
			Sq[0] = new Square();
			Sq[0].Side = 18.84;

			Sq[1] = new Square();
			Sq[1].Side = 25.62;

			Console.WriteLine("Squares Characteristics");
			Console.WriteLine("\nFirst Square");
			Console.WriteLine("Side:      {0}", Sq[0].Side);
			Console.WriteLine("Perimeter: {0}", Sq[0].Perimeter);
			Console.WriteLine("Area:      {0}", Sq[0].Area);
			
			Console.WriteLine("\nSecond Square");
			Console.WriteLine("Side:      {0}", Sq[1].Side);
			Console.WriteLine("Perimeter: {0}", Sq[1].Perimeter);
			Console.WriteLine("Area:      {0}", Sq[1].Area);
		}
	}
}

This would produce:

Squares Characteristics

First Square
Side:      18.84
Perimeter: 75.36
Area:      354.9456

Second Square
Side:      25.62
Perimeter: 102.48
Area:      656.3844
 

Practical LearningPractical Learning: Declaring an Array Variable of a Class

  1. To declare and use an array variable of StoreItem values, change the contents of the Main() method of the Exercise.cs as follows:
     
    using System;
    
    namespace DepartmentStore
    {
    	public class OrderProcessing
    	{
    		static void Main()
    		{
    			StoreItem[] anItem = new StoreItem[20];
    
    			// We will use a string to categorize each item
    			string Category;
    
    			// Create the list of sales items
    			anItem[0] = new StoreItem();
    			anItem[0].ItemNumber = 947783;
    			anItem[0].ItemName   = "Double-faced wool coat    ";
    			anItem[0].UnitPrice  = 275.25M;
    				
    			anItem[1] = new StoreItem();
    			anItem[1].ItemNumber = 934687;
    			anItem[1].ItemName   = "Floral Silk Tank Blouse   ";
    			anItem[1].UnitPrice  = 180.00M;
    				
    			anItem[2] = new StoreItem();
    			anItem[2].ItemNumber = 973947;
    			anItem[2].ItemName   = "Push Up Bra               ";
    			anItem[2].UnitPrice  = 50.00M;
    				
    			anItem[3] = new StoreItem();
    			anItem[3].ItemNumber = 987598;
    			anItem[3].ItemName   = "Chiffon Blouse            ";
    			anItem[3].UnitPrice  = 265.00M;
    				
    			anItem[4] = new StoreItem();
    			anItem[4].ItemNumber = 974937;
    			anItem[4].ItemName   = "Bow Belt Skirtsuit        ";
    			anItem[4].UnitPrice  = 245.55M;
    
    			anItem[5] = new StoreItem();
    			anItem[5].ItemNumber = 743765;
    			anItem[5].ItemName   = "Cable-knit Sweater        ";
    			anItem[5].UnitPrice  = 45.55M;
    
    			anItem[6] = new StoreItem();
    			anItem[6].ItemNumber = 747635;
    			anItem[6].ItemName   = "Jeans with Heart Belt     ";
    			anItem[6].UnitPrice  = 25.65M;
    			
    			anItem[7] = new StoreItem();
    			anItem[7].ItemNumber = 765473;
    			anItem[7].ItemName   = "Fashionable mini skirt    ";
    			anItem[7].UnitPrice  = 34.55M;
    			
    			anItem[8] = new StoreItem();
    			anItem[8].ItemNumber = 754026;
    			anItem[8].ItemName   = "Double Dry Pants          ";
    			anItem[8].UnitPrice  = 28.55M;
    			
    			anItem[9] = new StoreItem();
    			anItem[9].ItemNumber = 730302;
    			anItem[9].ItemName   = "Romantic Flower Dress     ";
    			anItem[9].UnitPrice  = 24.95M;
    			
    			anItem[10] = new StoreItem();
    			anItem[10].ItemNumber = 209579;
    			anItem[10].ItemName   = "Cotton Polo Shirt         ";
    			anItem[10].UnitPrice  = 45.75M;
    			
    			anItem[11] = new StoreItem();
    			anItem[11].ItemNumber = 267583;
    			anItem[11].ItemName   = "Pure Wool Cap             ";
    			anItem[11].UnitPrice  = 25.00M;
    			
    			anItem[12] = new StoreItem();
    			anItem[12].ItemNumber = 248937;
    			anItem[12].ItemName   = "Striped Cotton Shirt      ";
    			anItem[12].UnitPrice  = 65.55M;
    			
    			anItem[13] = new StoreItem();
    			anItem[13].ItemNumber = 276057;
    			anItem[13].ItemName   = "Two-Toned Ribbed Crewneck ";
    			anItem[13].UnitPrice  = 9.75M;
    			
    			anItem[14] = new StoreItem();
    			anItem[14].ItemNumber = 267945;
    			anItem[14].ItemName   = "Chestnut Italian Shoes    ";
    			anItem[14].UnitPrice  = 165.75M;
    			
    			anItem[15] = new StoreItem();
    			anItem[15].ItemNumber = 409579;
    			anItem[15].ItemName   = "Collar and Placket Jacket ";
    			anItem[15].UnitPrice  = 265.15M;
    			
    			anItem[16] = new StoreItem();
    			anItem[16].ItemNumber = 467583;
    			anItem[16].ItemName   = "Country Coat Rugged Wear  ";
    			anItem[16].UnitPrice  = 35.55M;
    			
    			anItem[17] = new StoreItem();
    			anItem[17].ItemNumber = 448937;
    			anItem[17].ItemName   = "Carpenter Jeans           ";
    			anItem[17].UnitPrice  = 24.95M;
    			
    			anItem[18] = new StoreItem();
    			anItem[18].ItemNumber = 476057;
    			anItem[18].ItemName   = "Dbl-Cushion Tennis Shoes  ";
    			anItem[18].UnitPrice  = 48.75M;
    			
    			anItem[19] = new StoreItem();
    			anItem[19].ItemNumber = 467945;
    			anItem[19].ItemName   = "Stitched Center-Bar Belt  ";
    			anItem[19].UnitPrice  = 32.50M;
    
    			// Display the inventory
    			Console.WriteLine("Store Inventory");
    			Console.WriteLine("=======+==========+===========================+=========");
    			Console.WriteLine("Item # | Category | Description               | Price");
    			for(int i = 0; i < 20; i++)
    			{
    				// Any item whose number starts with 9 is categorized as "Women"
    				if( anItem[i].ItemNumber >= 900000 )
    					Category = " Women";
    				// Any item whose number starts with 7 is for teenage girls
    				else if( anItem[i].ItemNumber >= 700000 )
    					Category = " Girls";
    				// Items whose number start with 4 are for teenage boyes
    				else if( anItem[i].ItemNumber >= 400000 )
    					Category = " Boys ";
    				else
    					Category = " Men  ";
                    
    				Console.WriteLine("-------+----------+---------------------------+---------");
    				Console.WriteLine("{0} | {1}   | {2}| {3}",
    					              anItem[i].ItemNumber, Category,
    					anItem[i].ItemName, anItem[i].UnitPrice);
    			}
    
    			Console.WriteLine("=======+==========+===========================+=========\n");
    		}
    	}
    }
  2. Save the Exercise.cs file
  3. To compile it, type csc /reference:ItemManager.dll /out:"Emilie Department Store".exe Exercise.cs
  4. To execute it, type "Emilie Department Store" and press Enter. This would produce:
     
    C:\CSharp Lessons\DeptStore6>csc /reference:ItemManager.dll /out:"Emilie Departm
    ent Store".exe 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\DeptStore6>"Emilie Department Store"
    Store Inventory
    =======+==========+===========================+=========
    Item # | Category | Description               | Price
    -------+----------+---------------------------+---------
    947783 |  Women   | Double-faced wool coat    | 275.25
    -------+----------+---------------------------+---------
    934687 |  Women   | Floral Silk Tank Blouse   | 180.00
    -------+----------+---------------------------+---------
    973947 |  Women   | Push Up Bra               | 50.00
    -------+----------+---------------------------+---------
    987598 |  Women   | Chiffon Blouse            | 265.00
    -------+----------+---------------------------+---------
    974937 |  Women   | Bow Belt Skirtsuit        | 245.55
    -------+----------+---------------------------+---------
    743765 |  Girls   | Cable-knit Sweater        | 45.55
    -------+----------+---------------------------+---------
    747635 |  Girls   | Jeans with Heart Belt     | 25.65
    -------+----------+---------------------------+---------
    765473 |  Girls   | Fashionable mini skirt    | 34.55
    -------+----------+---------------------------+---------
    754026 |  Girls   | Double Dry Pants          | 28.55
    -------+----------+---------------------------+---------
    730302 |  Girls   | Romantic Flower Dress     | 24.95
    -------+----------+---------------------------+---------
    209579 |  Men     | Cotton Polo Shirt         | 45.75
    -------+----------+---------------------------+---------
    267583 |  Men     | Pure Wool Cap             | 25.00
    -------+----------+---------------------------+---------
    248937 |  Men     | Striped Cotton Shirt      | 65.55
    -------+----------+---------------------------+---------
    276057 |  Men     | Two-Toned Ribbed Crewneck | 9.75
    -------+----------+---------------------------+---------
    267945 |  Men     | Chestnut Italian Shoes    | 165.75
    -------+----------+---------------------------+---------
    409579 |  Boys    | Collar and Placket Jacket | 265.15
    -------+----------+---------------------------+---------
    467583 |  Boys    | Country Coat Rugged Wear  | 35.55
    -------+----------+---------------------------+---------
    448937 |  Boys    | Carpenter Jeans           | 24.95
    -------+----------+---------------------------+---------
    476057 |  Boys    | Dbl-Cushion Tennis Shoes  | 48.75
    -------+----------+---------------------------+---------
    467945 |  Boys    | Stitched Center-Bar Belt  | 32.50
    =======+==========+===========================+=========
  5. Return to Notepad
  6. To be able to process an order, change the file as follows:
     
    using System;
    
    namespace DepartmentStore
    {
    	public class OrderProcessing
    	{
    		static void Main()
    		{
    			StoreItem[] anItem = new StoreItem[20];
    
    			// Create the list of sales items
    			anItem[0] = new StoreItem();
    			
    			
    			. . . No Change
    			
    			
    			anItem[19] = new StoreItem();
    			anItem[19].ItemNumber = 467945;
    			anItem[19].ItemName   = "Stitched Center-Bar Belt  ";
    			anItem[19].UnitPrice  = 32.50M;
    
    			long    ItemID = 0;
    			string  Description = "Unknown";
    			decimal Price = 0.00M;
    			// We will use a string to categorize each item
    			string Category = "Category";
    
    			// Order Processing
     			// Request an item number from the user
    			try 
    			{
    				Console.Write("Enter Item Number: ");
    				ItemID = long.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    				Console.WriteLine("Invalid Number - The program will terminate\n");
    			}
    
    			// Scan the list
    			for(int i = 0; i < 20; i++)
    			{
    				// Find out if the number typed exists in the list
    				if( ItemID == anItem[i].ItemNumber )
    				{
    					// If the number matches one of the numbers in the list
    					// Create a StoreItem value from it
    					Description = anItem[i].ItemName;
    					Price = anItem[i].UnitPrice;
                        
    					// Identify the category of the item
    					if( ItemID >= 900000 )
    						Category = "Women";
    					else if( ItemID >= 700000 )
    						Category = "Girls";
    					else if( ItemID >= 400000 )
    						Category = "Boys";
    					else
    						Category = "Men";
    				}
    			}
    
    			// Display the receipt
    			Console.WriteLine("Receipt");
    			Console.WriteLine("Item Number: {0}", ItemID);
    			Console.WriteLine("Description: {0} - {1}", Category, Description);
    			Console.WriteLine("Unit Price:  {0:C}\n", Price);
    		}
    	}
    }
  7. Save the file
  8. To compile it, type csc /reference:ItemManager.dll /out:"Emilie Department Store".exe Exercise.cs and press Enter
  9. To execute the program, "Emilie Department Store" and press Enter. Here is an example:
     
    Enter Item Number: 448937
    Receipt
    Item Number: 448937
    Description: Boys - Carpenter Jeans
    Unit Price:  $24.95
  10. Return to Notepad
 

A Class Array Passed as Argument

Like a primitive type, a class can be passed to a function as argument. Everything is primarily done the same except that, since the argument is an array, each member of the array is a variable in its own right, with a value for each member variable of the class. Based on this, when dealing with the argument, you can access each of its members individually using its index.

Practical LearningPractical Learning: Passing a Class as Argument

  1. To pass an array of a class to a method as argument, change the file as follows:
     
    using System;
    
    namespace DepartmentStore
    {
    	public class OrderProcessing
    	{
    		static void Main()
    		{
    			StoreItem[] SaleItem = new StoreItem[20];
    
    			CreateInventory(SaleItem);
    
    			int Choice = 1;
    
    			Console.WriteLine("Welcome to Emilie Department Store");
    			// Present a short menu to the user
    			do
    			{
    				// Let the user specify the action to take
    				try 
    				{
    					Console.WriteLine("What action do you want to take?");
    					Console.WriteLine("1 - I want to see the store inventory");
    					Console.WriteLine("2 - I want to process a customer order");
    					Console.Write("Your Choice? ");
    					Choice = int.Parse(Console.ReadLine());
    				}
    				catch(FormatException)
    				{
    					Console.WriteLine("Invalid choice - The character you typed is excluded!");
    				}
    					
    				if( Choice != 1 && Choice != 2 )
    					Console.WriteLine("Invalid Number - Please Try Again!\n");
    			} while( Choice != 1 && Choice != 2 );
    
    			// Take action based on the user's choice
    			if( Choice == 1 )
    				ShowInventory(SaleItem);
    			else
    				ProcessOrder(SaleItem);
    		}
    
    		// This method is used to process an order
    		// It fills a StoreItem array argument passed to it
    		static void ProcessOrder(StoreItem[] Order)
    		{
    			string  Category = "Category";
    			long    ItemID = 0;
    			string  Description = "Unknown";
    			decimal Price = 0.00M;
    
    			// Order Processing
     			// Request an item number from the user
    			try 
    			{
    				Console.Write("Enter Item Number: ");
    				ItemID = long.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    				Console.WriteLine("Invalid Number - The program will terminate\n");
    			}
    
    			// Scan the list
    			for(int i = 0; i < 20; i++)
    			{
    				// Find out if the number typed exists in the list
    				if( ItemID == Order[i].ItemNumber )
    				{
    					// If the number matches one of the itemsin the list
    					// get the characteristics of that item
    					Description = Order[i].ItemName;
    					Price = Order[i].UnitPrice;
                        
    					// Identify the category of the item
    					if( ItemID >= 900000 )
    						Category = "Women";
    					else if( ItemID >= 700000 )
    						Category = "Girls";
    					else if( ItemID >= 400000 )
    						Category = "Boys";
    					else
    						Category = "Men";
    				}
    			}
    
    			Console.WriteLine("Receipt");
    			Console.WriteLine("Item Number: {0}", ItemID);
    			Console.WriteLine("Description: {0} - {1}", Category, Description);
    			Console.WriteLine("Unit Price:  {0:C}\n", Price);
    
    			Console.WriteLine();
    		}
    		
    		// This method can be called to display the current inventory of the store
    		static void ShowInventory(StoreItem[] Items)
    		{
    			// Display the inventory
    			string  Category = "Category";
    			Console.WriteLine("Store Inventory");
    			Console.WriteLine("=======+==========+===========================+=========");
    			Console.WriteLine("Item # | Category | Description               | Price");
    			for(int i = 0; i < 20; i++)
    			{
    				if( Items[i].ItemNumber >= 900000 )
    					Category = " Women";
    				else if( Items[i].ItemNumber >= 700000 )
    					Category = " Girls";
    				else if( Items[i].ItemNumber >= 400000 )
    					Category = " Boys ";
    				else
    					Category = " Men  ";
                    
    				Console.WriteLine("-------+----------+---------------------------+---------");
    				Console.WriteLine("{0} | {1}   | {2}| {3}",
    					Items[i].ItemNumber, Category,
    					Items[i].ItemName, Items[i].UnitPrice);
    			}
    
    			Console.WriteLine("=======+==========+===========================+=========\n");
    		}
    
    		// This method creates an inventory of the items available in the store
    		// It receives an empty list as a StoreItem array but fills it with the necessary item
    		static void CreateInventory(StoreItem[] anItem)
    		{
    			// Create the list of sales items
    			anItem[0] = new StoreItem();
    			anItem[0].ItemNumber = 947783;
    			anItem[0].ItemName   = "Double-faced wool coat    ";
    			anItem[0].UnitPrice  = 275.25M;
    				
    			anItem[1] = new StoreItem();
    			anItem[1].ItemNumber = 934687;
    			anItem[1].ItemName   = "Floral Silk Tank Blouse   ";
    			anItem[1].UnitPrice  = 180.00M;
    				
    			anItem[2] = new StoreItem();
    			anItem[2].ItemNumber = 973947;
    			anItem[2].ItemName   = "Push Up Bra               ";
    			anItem[2].UnitPrice  = 50.00M;
    				
    			anItem[3] = new StoreItem();
    			anItem[3].ItemNumber = 987598;
    			anItem[3].ItemName   = "Chiffon Blouse            ";
    			anItem[3].UnitPrice  = 265.00M;
    				
    			anItem[4] = new StoreItem();
    			anItem[4].ItemNumber = 974937;
    			anItem[4].ItemName   = "Bow Belt Skirtsuit        ";
    			anItem[4].UnitPrice  = 245.55M;
    
    			anItem[5] = new StoreItem();
    			anItem[5].ItemNumber = 743765;
    			anItem[5].ItemName   = "Cable-knit Sweater        ";
    			anItem[5].UnitPrice  = 45.55M;
    
    			anItem[6] = new StoreItem();
    			anItem[6].ItemNumber = 747635;
    			anItem[6].ItemName   = "Jeans with Heart Belt     ";
    			anItem[6].UnitPrice  = 25.65M;
    			
    			anItem[7] = new StoreItem();
    			anItem[7].ItemNumber = 765473;
    			anItem[7].ItemName   = "Fashionable mini skirt    ";
    			anItem[7].UnitPrice  = 34.55M;
    			
    			anItem[8] = new StoreItem();
    			anItem[8].ItemNumber = 754026;
    			anItem[8].ItemName   = "Double Dry Pants          ";
    			anItem[8].UnitPrice  = 28.55M;
    			
    			anItem[9] = new StoreItem();
    			anItem[9].ItemNumber = 730302;
    			anItem[9].ItemName   = "Romantic Flower Dress     ";
    			anItem[9].UnitPrice  = 24.95M;
    			
    			anItem[10] = new StoreItem();
    			anItem[10].ItemNumber = 209579;
    			anItem[10].ItemName   = "Cotton Polo Shirt         ";
    			anItem[10].UnitPrice  = 45.75M;
    			
    			anItem[11] = new StoreItem();
    			anItem[11].ItemNumber = 267583;
    			anItem[11].ItemName   = "Pure Wool Cap             ";
    			anItem[11].UnitPrice  = 25.00M;
    			
    			anItem[12] = new StoreItem();
    			anItem[12].ItemNumber = 248937;
    			anItem[12].ItemName   = "Striped Cotton Shirt      ";
    			anItem[12].UnitPrice  = 65.55M;
    			
    			anItem[13] = new StoreItem();
    			anItem[13].ItemNumber = 276057;
    			anItem[13].ItemName   = "Two-Toned Ribbed Crewneck ";
    			anItem[13].UnitPrice  = 9.75M;
    			
    			anItem[14] = new StoreItem();
    			anItem[14].ItemNumber = 267945;
    			anItem[14].ItemName   = "Chestnut Italian Shoes    ";
    			anItem[14].UnitPrice  = 165.75M;
    			
    			anItem[15] = new StoreItem();
    			anItem[15].ItemNumber = 409579;
    			anItem[15].ItemName   = "Collar and Placket Jacket ";
    			anItem[15].UnitPrice  = 265.15M;
    			
    			anItem[16] = new StoreItem();
    			anItem[16].ItemNumber = 467583;
    			anItem[16].ItemName   = "Country Coat Rugged Wear  ";
    			anItem[16].UnitPrice  = 35.55M;
    			
    			anItem[17] = new StoreItem();
    			anItem[17].ItemNumber = 448937;
    			anItem[17].ItemName   = "Carpenter Jeans           ";
    			anItem[17].UnitPrice  = 24.95M;
    			
    			anItem[18] = new StoreItem();
    			anItem[18].ItemNumber = 476057;
    			anItem[18].ItemName   = "Dbl-Cushion Tennis Shoes  ";
    			anItem[18].UnitPrice  = 48.75M;
    			
    			anItem[19] = new StoreItem();
    			anItem[19].ItemNumber = 467945;
    			anItem[19].ItemName   = "Stitched Center-Bar Belt  ";
    			anItem[19].UnitPrice  = 32.50M;
    		}
    	}
    }
  2. Save the file
  3. Compile the program with csc /reference:ItemManager.dll /out:"Emilie Department Store".exe Exercise.cs
  4. Execute it with "Emilie Department Store"
  5. Return to Notepad

Returning a Class Array From a Method

Once again, like a regular variable, an array can be returned from a function. The syntax also follows that of a primitive type. When the function ends, you must make sure it returns an array and not a regular variable.

 

Practical LearningPractical Learning: Return a Class Array From a Function

  1. To return an array from a method, change the file as follows:
     
    using System;
    
    namespace DepartmentStore
    {
    	public class OrderProcessing
    	{
    		static void Main()
    		{
    			StoreItem[] SaleItem = new StoreItem[20];
    
    			SaleItem = CreateInventory();
    
    			int Choice = 1;
    
    			Console.WriteLine("Welcome to our Department Store");
    			do 
    			{
    				try 
    				{
    					Console.WriteLine("What action do you want to take?");
    					Console.WriteLine("1 - I want to see the store inventory");
    					Console.WriteLine("2 - I want to process a customer order");
    					Console.Write("Your Choice? ");
    					Choice = int.Parse(Console.ReadLine());
    				}
    				catch(FormatException)
    				{
    					Console.WriteLine("Invalid choice - The character you typed is excluded!");
    				}
    				ed Center-Bar Belt  ";
    			anItem[19].UnitPrice  = 32.50M;
    
    			return anItem;
    		}
    	}
    }
  2. Compile and execute the application
  3. To use the foreach keyword, change the Exercise.cs file as follows:
     
    using System;
    
    namespace DepartmentStore
    {
    	public class OrderProcessing
    	{
    		static void Main()
    		{
    			StoreItem[] SaleItem = new StoreItem[20];
    
    			SaleItem = CreateInventory();
    
    			int Choice = 1;
    
    			Console.WriteLine("Welcome to Emilie Department Store");
    			
    			. . . No Change
    		}
    
    		// This method is used to process an order
    		// It fills a StoreItem array argument passed to it
    		static void ProcessOrder(StoreItem[] Order)
    		{
    			. . . No Change
    		}
    		
    		// This method can be called to display the current inventory of the store
    		static void ShowInventory(StoreItem[] Items)
    		{
    			. . . No Change
    		}
    
    		// This method creates an inventory of the items available in the store
    		// It initializes a StoreItem array with the necessary item and returns it
    		static StoreItem[] CreateInventory()
    		{
    			StoreItem[] anItem = new StoreItem[20];
    
    			// Create the list of sales items
    			anItem[0] = new StoreItem();
    			
    			. . . No Change
    
    			return anItem;
    		}
    	}
    }
  4. Save, compile, and execute the application
 

Previous Copyright 2004-2006 FunctionX, Inc. Next