Besides the ability to create a collection, the ArrayList
class has the built-in mechanism for serialization.
The ArrayList class is defined in the
System.Collections namespace. Therefore, in order to use the ArrayList
class in your application, you can first include the System.Collections
namespace in the file that would perform ArrayList operations.
Practical Learning: Introducing the ArrayList Class
|
|
- Start Microsoft Visual C# and create a new Console Application named
RealEstate5
- To save the project, on the Standard toolbar, click the Save All button
- Accept the suggestions and click Save
- To create a new class, in the Solution Explorer, right-click RealEstate5
-> Add -> Class...
- Set the Name to Property and click Add
- Change the file as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RealEstate5
{
public enum PropertyCondition
{
Unknown,
Excellent,
Good,
NeedsRepair,
BadShape
}
[Serializable]
public class Property
{
private string propNbr;
private PropertyCondition cond;
private short beds;
private float baths;
private int yr;
private decimal val;
public string PropertyNumber
{
get { return propNbr; }
set
{
if (propNbr == "")
propNbr = "N/A";
else
propNbr = value;
}
}
public string PropertyType;
public PropertyCondition Condition
{
get { return cond; }
set { cond = value; }
}
public short Bedrooms
{
get
{
if (beds <= 1)
return 1;
else
return beds;
}
set { beds = value; }
}
public float Bathrooms
{
get { return (baths <= 0) ? 0.00f : baths; }
set { baths = value; }
}
public int YearBuilt
{
get { return yr; }
set { yr = value; }
}
public decimal Value
{
get { return (val <= 0) ? 0.00M : val; }
set { val = value; }
}
}
}
|
- To create a new class, in the Class View, right-click RealEstate5 -> Add
-> Class...
- Set the Name to Condominium and press Enter
- Change the file as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RealEstate5
{
[Serializable]
public class Condominium : Property
{
private bool handicap;
public Condominium()
{
this.PropertyType = "Condominium";
}
public bool HandicapAccessible
{
get { return handicap; }
set { handicap = value; }
}
}
}
|
|
- To create a new class, on the main menu, click Project -> Add Class...
- Set the Name to HouseType and click Add
- Change the file as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RealEstate5
{
[Serializable]
public class HouseType : Property
{
private short nbrOfStories;
private bool basement;
private bool garage;
public short Stories
{
get { return nbrOfStories; }
set { nbrOfStories = value; }
}
public bool FinishedBasement
{
get { return basement; }
set { basement = value; }
}
public bool IndoorGarage
{
get { return garage; }
set { garage = value; }
}
}
}
|
- To create a new class, in the Solution Explorer, right-click RealEstate5
-> Add -> Class...
- Set the Name to Townhouse and press Enter
- Change the file as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RealEstate5
{
[Serializable]
public class Townhouse : HouseType
{
private bool comm;
public Townhouse()
{
this.PropertyType = "Townhouse";
}
public bool IsCommunityManaged
{
get { return this.comm; }
set { this.comm = value; }
}
}
}
|
- To create a new class, in the Class View, right-click RealEstate5 -> Add
-> Class...
- Set the Name to SingleFamily and click Add
- Change the file as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RealEstate5
{
[Serializable]
public class SingleFamily : HouseType
{
public SingleFamily()
{
this.PropertyType = "Single Family";
}
}
}
|
- Save all
After declaring an ArrayList variable, it is empty.
As objects are added to it, the list grows. The list can grow tremendously as
you wish. The number of items of the list is managed through the memory it
occupies and this memory grows as needed. The number of items that the memory
allocated is currently using is represented by the ArrayList.Capacity
property. This will usually be the least of your concerns.
If for some reason, you want to intervene and control the
number of items that your ArrayList list can contain, you can manipulate
the Capacity property. For example, you can assign it a constant to set
the maximum value that the list can contain. Once again, you will hardly have
any reason to use the Capacity property: the compiler knows what to do
with it.
If you set a fixed size on an ArrayList list, you may
not be able to add a new item beyond the limit. In fact, if you attempt to do
this, you may receive an error. A safe way is to check whether the list is fixed
before performing a related operation. To find out whether a list is fixed, you
can check the ArrayList variable's IsFixedSize property.
One of the reason for creating a list is to be able to add
items to it, edit its items, retrieve an items, or delete items from it. These
are the default operations. You can still limit these operations as you judge
them unnecessary. For example, you may create a list and then initialize it with
the items that you want the list to only have. If you don't intend to have the
user adding items to it, you can create the list as read-only. To do this, you
can call the ArrayList.ReadOnly() method. It is overloaded with two
versions as follows:
public static ArrayList ReadOnly(ArrayList);
public static IList ReadOnly(IList);
This method is static. This means that you don't need to
declare an instance of ArrayList to call them. Instead, to make the list
read-only, call the ArrayList.ReadOnly() method and pass your
ArrayList variable to it.
As we will see in the next sections, some operations cannot
be performed on a read-only list. To perform such operations, you can first find
out whether an ArrayList list is read-only. This is done by checking its
IsReadOnly property.
The primary operation performed on a list is to create one.
One of the biggest advantages of using a linked list is that you don't have to
specify in advance the number of items of the list as done for an array. You can
just start adding items. The ArrayList class makes this possible with the
Add() method. Its syntax is:
public virtual int Add(object value);
The argument of this method is the value to add to the list.
If the method succeeds with the addition, it returns the position where the
value was added in the list. This is usually the last position in the list. If
the method fails, the compiler would throw an error. One of the errors that
could result from failure of this operation would be based on the fact that
either a new item cannot be added to the list because the list is read-only, or
the list was already full prior to adding the new item. Normally, a list can be
full only if you had specified the maximum number of items it can contain using
the ArrayList.Capacity property. As mentioned above, the list can be made
read-only by passing its variable to the ArrayList.ReadOnly() method
Practical Learning: Adding Items to an ArrayList List
|
|
- To create an inventory, on the main menu, click Project -> Add Class...
- Set the Name to PropertyManagement and press Enter
- Change the file as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
namespace RealEstate5
{
public class PropertyManagement
{
private Condominium Condo;
private Townhouse TownHome;
private SingleFamily House;
private ArrayList Condominiums;
private ArrayList Townhouses;
private ArrayList SingleFamilies;
private string strPropertyNumber;
private string strPropertiesDirectory;
public PropertyManagement()
{
Condo = new Condominium();
TownHome = new Townhouse();
House = new SingleFamily();
Condominiums = new ArrayList();
Townhouses = new ArrayList();
SingleFamilies = new ArrayList();
strPropertyNumber = "000000";
strPropertiesDirectory = @"C:\Altair Realty\Properties";
try
{
// If a directory for the properties has not yet
// been created, then create them
Directory.CreateDirectory(strPropertiesDirectory);
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("The directory could " +
"not be created");
}
}
public PropertyCondition GetPropertyCondition()
{
short condition = 0;
try
{
Console.WriteLine("\nProperties Conditions");
Console.WriteLine("1. Excellent");
Console.WriteLine("2. Good (may need minor repair)");
Console.WriteLine("3. Needs Repair");
Console.Write("4. In Bad Shape (property needs ");
Console.WriteLine("major repair or rebuild)");
Console.Write("Enter Property Condition: ");
condition = short.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("The value you entered for " +
"the condition of the property is not valid");
}
if (condition == 1)
return PropertyCondition.Excellent;
else if (condition == 2)
return PropertyCondition.Good;
else if (condition == 3)
return PropertyCondition.NeedsRepair;
else if (condition == 4)
return PropertyCondition.BadShape;
else
return PropertyCondition.Unknown;
}
public void CreateProperty()
{
char propType = '0';
Console.WriteLine("\n=======================");
Console.WriteLine(" =//= Altair Realty =//=");
Console.WriteLine("-=- Property Creation -=-");
Console.WriteLine("------------------------");
// We will make sure that no two
// properties have the same number
Console.Write("\nEnter Property #: ");
this.strPropertyNumber = Console.ReadLine();
try
{
Console.WriteLine("\nTypes of Properties");
Console.WriteLine("1. Condominium");
Console.WriteLine("2. Townhouse");
Console.WriteLine("3. Single Family");
Console.Write("Enter Type of Property: ");
propType = char.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("The value you entered for " +
"the type of property is invalid");
}
switch (propType)
{
case '1':
CreateCondominium();
break;
case '2':
CreateTownhouse();
break;
case '3':
CreateSingleFamily();
break;
default:
Console.WriteLine("Invalid Choice!!!");
break;
}
}
public void CreateCondominium()
{
char answer = 'n';
Condo.PropertyNumber = strPropertyNumber;
Condo.Condition = GetPropertyCondition();
try
{
Console.Write("\nHow many bedrooms? ");
Condo.Bedrooms = short.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("The value you entered for " +
"the number of bedrooms is not good");
}
try
{
Console.Write("How many bathrooms? ");
Condo.Bathrooms =
float.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Invalid value");
}
try
{
Console.Write("Year built: ");
Condo.YearBuilt =
int.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("The house cannot have " +
"built in that year");
}
Console.Write("\nIs the building " +
"accessible to handicapped (y/n): ");
answer = char.Parse(Console.ReadLine());
if ((answer == 'y') || (answer == 'Y'))
Condo.HandicapAccessible = true;
else
Condo.HandicapAccessible = false;
try
{
Console.Write("Condominium Value: ");
Condo.Value = decimal.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Invalid Property Value");
}
Condominiums.Add(Condo);
ShowTitle();
ShowCondominium();
SaveCondominium();
}
public void CreateTownhouse()
{
char answer = 'n';
this.TownHome.PropertyNumber = strPropertyNumber;
this.TownHome.Condition = GetPropertyCondition();
try
{
Console.Write("\nHow many stories (levels)? ");
this.TownHome.Stories =
short.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("The number of stories " +
"you entered is not valid");
}
try
{
Console.Write("How many bedrooms? ");
this.TownHome.Bedrooms =
short.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("The value you entered for " +
"the number of bedrooms is not good");
}
try
{
Console.Write("How many bathrooms? ");
this.TownHome.Bathrooms =
float.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Invalid bathroom number.");
}
Console.Write("Does it have an indoor " +
"car garage (y/n): ");
answer = char.Parse(Console.ReadLine());
if ((answer == 'y') || (answer == 'Y'))
this.TownHome.IndoorGarage = true;
else
this.TownHome.IndoorGarage = false;
Console.Write("Is the basement finished(y/n): ");
answer = char.Parse(Console.ReadLine());
if ((answer == 'y') || (answer == 'Y'))
this.TownHome.FinishedBasement = true;
else
this.TownHome.FinishedBasement = false;
try
{
Console.Write("Year built: ");
this.TownHome.YearBuilt =
int.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("The house cannot have " +
"built in that year");
}
try
{
Console.Write("Is it community managed (y/n)? ");
answer = char.Parse(Console.ReadLine());
if ((answer == 'y') || (answer == 'Y'))
this.TownHome.IsCommunityManaged = true;
else
this.TownHome.IsCommunityManaged = false;
}
catch (FormatException)
{
Console.WriteLine("Invalid Answer");
}
try
{
Console.Write("Property Value: ");
this.TownHome.Value = decimal.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Invalid Property Value");
}
Townhouses.Add(this.TownHome);
ShowTitle();
ShowTownhouse();
SaveTownhouse();
}
public void CreateSingleFamily()
{
char answer = 'n';
Console.WriteLine(" =//= Altair Realty =//=");
Console.WriteLine("-=- Property Creation -=-");
this.House.PropertyNumber = strPropertyNumber;
House.Condition = GetPropertyCondition();
try
{
Console.Write("\nHow many stories (levels)? ");
House.Stories = short.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("The number of stories you " +
"entered is not allowed");
}
try
{
Console.Write("How many bedrooms? ");
House.Bedrooms =
short.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("The value you entered for " +
"the number of bedrooms is not good");
}
try
{
Console.Write("How many bathrooms? ");
House.Bathrooms =
float.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Invalid number of bathrooms");
}
try
{
Console.Write("Does it have an indoor " +
"car garage (y/n): ");
answer = char.Parse(Console.ReadLine());
if ((answer == 'y') || (answer == 'Y'))
House.IndoorGarage = true;
else
House.IndoorGarage = false;
}
catch (FormatException)
{
Console.WriteLine("Invalid Indoor Car Garage Answer");
}
try
{
Console.Write("Is the basement finished(y/n): ");
answer = char.Parse(Console.ReadLine());
if ((answer == 'y') || (answer == 'Y'))
House.FinishedBasement = true;
else
House.FinishedBasement = false;
}
catch (FormatException)
{
Console.WriteLine("Invalid Basement Answer");
}
try
{
Console.Write("Year built: ");
House.YearBuilt =
int.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("The house cannot have " +
"built in that year");
}
try
{
Console.Write("House Value: ");
House.Value = decimal.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Invalid Property Value");
}
SingleFamilies.Add(House);
ShowTitle();
ShowSingleFamily();
SaveSingleFamily();
}
public void ShowTitle()
{
Console.WriteLine("==================================");
Console.WriteLine(" =//=//= Altair Realty =//=//=");
Console.WriteLine("-=-=-=- Properties Listing -=-=-=-");
}
public void ShowCondominium()
{
Console.WriteLine("----------------------------------");
Console.WriteLine("Property #: {0}",
Condo.PropertyNumber);
Console.WriteLine("Property Type: {0}",
Condo.PropertyType);
Console.WriteLine("Condition: {0}",
Condo.Condition);
Console.WriteLine("Bedrooms: {0}",
Condo.Bedrooms);
Console.WriteLine("Bathrooms: {0:F}",
Condo.Bathrooms);
Console.WriteLine("Year Built: {0}",
Condo.YearBuilt);
Console.WriteLine("Handicapped Accessible Building: {0}",
Condo.HandicapAccessible);
Console.WriteLine("Market Value: {0:C}",
Condo.Value);
Console.WriteLine("----------------------------------");
}
public void ShowTownhouse()
{
Console.WriteLine("----------------------------------");
Console.WriteLine("Property #: {0}",
TownHome.PropertyNumber);
Console.WriteLine("Property Type: {0}",
TownHome.PropertyType);
Console.WriteLine("Stories: {0}",
TownHome.Stories);
Console.WriteLine("Has Indoor Car Garage: {0}",
TownHome.IndoorGarage);
Console.WriteLine("Finished Basement: {0}",
TownHome.FinishedBasement);
Console.WriteLine("Condition: {0}",
TownHome.Condition);
Console.WriteLine("Bedrooms: {0}",
TownHome.Bedrooms);
Console.WriteLine("Bathrooms: {0:F}",
TownHome.Bathrooms);
Console.WriteLine("Year Built: {0}",
TownHome.YearBuilt);
Console.WriteLine("Community Managed? {0}",
TownHome.IsCommunityManaged);
Console.WriteLine("Market Value: {0:C}",
TownHome.Value);
Console.WriteLine("----------------------------------");
}
public void ShowSingleFamily()
{
Console.WriteLine("----------------------------------");
Console.WriteLine("Property #: {0}",
House.PropertyNumber);
Console.WriteLine("Property Type: {0}",
House.PropertyType);
Console.WriteLine("Stories: {0}",
House.Stories);
Console.WriteLine("Has Indoor Car Garage: {0}",
House.IndoorGarage);
Console.WriteLine("Finished Basement: {0}",
House.FinishedBasement);
Console.WriteLine("Condition: {0}",
House.Condition);
Console.WriteLine("Bedrooms: {0}",
House.Bedrooms);
Console.WriteLine("Bathrooms: {0:F}",
House.Bathrooms);
Console.WriteLine("Year Built: {0}",
House.YearBuilt);
Console.WriteLine("Market Value: {0:C}",
House.Value);
Console.WriteLine("----------------------------------");
}
public void SaveCondominium()
{
FileStream fsCondo = null;
BinaryFormatter bfCondo = new BinaryFormatter();
string strFilename = strPropertiesDirectory +
@"\Condominiums.alr";
try
{
fsCondo = new FileStream(strFilename,
FileMode.Create,
FileAccess.Write);
bfCondo.Serialize(fsCondo, Condominiums);
}
finally
{
fsCondo.Close();
}
}
public void SaveTownhouse()
{
FileStream fsTown = null;
BinaryFormatter bfTown =
new BinaryFormatter();
string strFilename = strPropertiesDirectory +
@"\Townhouses.alr";
try
{
fsTown = new FileStream(strFilename,
FileMode.Create,
FileAccess.Write);
bfTown.Serialize(fsTown, Townhouses);
}
finally
{
fsTown.Close();
}
}
public void SaveSingleFamily()
{
FileStream fsHouse = null;
BinaryFormatter bfHouse = new BinaryFormatter();
string strFilename = strPropertiesDirectory +
@"\SingleFamilies.alr";
try
{
fsHouse = new FileStream(strFilename,
FileMode.Create,
FileAccess.Write);
bfHouse.Serialize(fsHouse,
SingleFamilies);
}
finally
{
fsHouse.Close();
}
}
}
}
|
- Access the Program.cs file and change it as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RealEstate5
{
public class Program
{
static void Main(string[] args)
{
var answer = 'q';
var listing = new PropertyManagement();
// Display the title
Console.WriteLine("=================================");
Console.WriteLine(" =//= Altair Realty =//=");
Console.WriteLine("----------------------------------");
do
{
// Ask the user to select an option
try
{
Console.WriteLine("What do you want to do?");
Console.WriteLine("1. Create a property");
Console.WriteLine("0. Quit");
Console.Write("Your Choice? ");
answer = char.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Invalid Choice!!!");
}
switch (answer)
{
case '1':
listing.CreateProperty();
break;
default:
break;
}
} while(answer == '1');
Console.WriteLine();
}
}
}
|
- Execute the application and continually create the following properties:
=================================
=//= Altair Realty =//=
----------------------------------
What do you want to do?
1. Create a property
0. Quit
Your Choice? 1
=======================
=//= Altair Realty =//=
-=- Property Creation -=-
------------------------
Enter Property #: 000001
Types of Properties
1. Condominium
2. Townhouse
3. Single Family
Enter Type of Property: 1
Properties Conditions
1. Excellent
2. Good (may need minor repair)
3. Needs Repair
4. In Bad Shape (property needs major repair or rebuild)
Enter Property Condition: 1
How many bedrooms? 1
How many bathrooms? 1
Year built: 1960
Is the building accessible to handicapped (y/n): n
Condominium Value: 10000
==================================
=//=//= Altair Realty =//=//=
-=-=-=- Properties Listing -=-=-=-
----------------------------------
Property #: 000001
Property Type: Condominium
Condition: Excellent
Bedrooms: 1
Bathrooms: 1.00
Year Built: 1960
Handicapped Accessible Building: False
Market Value: $10,000.00
----------------------------------
What do you want to do?
1. Create a property
0. Quit
Your Choice? 1
=======================
=//= Altair Realty =//=
-=- Property Creation -=-
------------------------
Enter Property #: 000002
Types of Properties
1. Condominium
2. Townhouse
3. Single Family
Enter Type of Property: 2
Properties Conditions
1. Excellent
2. Good (may need minor repair)
3. Needs Repair
4. In Bad Shape (property needs major repair or rebuild)
Enter Property Condition: 1
How many stories (levels)? 1
How many bedrooms? 1
How many bathrooms? 1
Does it have an indoor car garage (y/n): n
Is the basement finished(y/n): n
Year built: 1960
Is it community managed (y/n)? n
Property Value: 20000
==================================
=//=//= Altair Realty =//=//=
-=-=-=- Properties Listing -=-=-=-
----------------------------------
Property #: 000002
Property Type: Townhouse
Stories: 1
Has Indoor Car Garage: False
Finished Basement: False
Condition: Excellent
Bedrooms: 1
Bathrooms: 1.00
Year Built: 1960
Community Managed? False
Market Value: $20,000.00
----------------------------------
What do you want to do?
1. Create a property
0. Quit
Your Choice? 1
=======================
=//= Altair Realty =//=
-=- Property Creation -=-
------------------------
Enter Property #: 000003
Types of Properties
1. Condominium
2. Townhouse
3. Single Family
Enter Type of Property: 3
=//= Altair Realty =//=
-=- Property Creation -=-
Properties Conditions
1. Excellent
2. Good (may need minor repair)
3. Needs Repair
4. In Bad Shape (property needs major repair or rebuild)
Enter Property Condition: 1
How many stories (levels)? 1
How many bedrooms? 1
How many bathrooms? 1
Does it have an indoor car garage (y/n): n
Is the basement finished(y/n): n
Year built: 1960
House Value: 30000
==================================
=//=//= Altair Realty =//=//=
-=-=-=- Properties Listing -=-=-=-
----------------------------------
Property #: 000003
Property Type: Single Family
Stories: 1
Has Indoor Car Garage: False
Finished Basement: False
Condition: Excellent
Bedrooms: 1
Bathrooms: 1.00
Year Built: 1960
Market Value: $30,000.00
----------------------------------
What do you want to do?
1. Create a property
0. Quit
Your Choice? 0
Press any key to continue . . .
|
- Close the DOS window
|
|