Home

C++/CLI Collections:
Populating the Collection

 

Adding an Item to the Collection

As it should be obvious, the primary operation to perform on a list is to populate it with at least one item. To support this, the IList interface is equipped with a method named Add. Its syntax is:

int Add(Object ^ value);

This method takes one argument as the object to add to the collection. If your collection is an array, you can first check that there is still enough room in the collection to add a new item. In reality, this is never an issue with the IList interface:

  • If there is still room in the collection, the item would be added to the list
  • If there is not enough room, the item would simply not be added. There would not be a problem and the program would not crash. In fact, no exception would be thrown if the item was not added because of lack of space. On the other, since the compiler would not let you know that there was a problem with "logistic", you may not know whether the item was added or not. Therefore, if you are concerned with known whether the item was added, you must provide this functionality yourself 

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.

Here is an example:

public ref class CObjects : public IList
{
private:
    int items;
    array<Object ^> ^ objects;

public:
    . . . No Change

    virtual int Add(Object ^ value);
};

. . . No Change

int CObjects::Add(Object ^ value)
{
    // Check whether there is still room in
    // the array to add a new item
    if( items < objects->Length )
    {
        // Since there is room, put the new item to the end
	objects[items] = value;
	// increase the number of items
	items++;
	// Return the index of the item that was added
	return items - 1;
    } // Since the item could not be added, return a negative index
    else
	return -1;
}

Practical Learning Practical Learning: Adding an Item to the Collection

  1. In the Scopes combo box of the Code Editor, select CProperties and, in the Functions combo box, select Add
  2. Implement the method as follows:
     
    // This method is used to add a new item to the collection
    int CProperties::Add(Object ^ value)
    {
        // Find out if the array is getting too small for the next item(s)
        // If it is, increase its size by 5
        if( Count == RentalProperties->Length )
    	Array::Resize(customers, customers->Length + 5);
    
        if( counter < RentalProperties->Length )
        {
    	RentalProperties[counter] = value;
    	counter++;
    	return counter - 1;
        }
        else
    	return -1;
    }
  3. In the Class View, right-click CProperties -> Add -> Function...
  4. In the Return Type combo box, type CRentalProperty ^
  5. Set the Function Name to Get
  6. In the Parameter Type, select int
  7. In the Parameter Name, type index and click Add
     
  8. Click Finish
  9. Implement the method as follows:
     
    // This method is used to get the property positioned
    // at the index passed as argument
    CRentalProperty ^ CProperties::Get(int index)
    {
        return dynamic_cast<CRentalProperty ^>(RentalProperties[index]);
    }
  10. Open the Exercise.cpp source file and change it as follows:
     
    #include "RentalProperty.h"
    #include "Properties.h"
    
    using namespace System;
    
    int main()
    {
        CProperties ^ properties = gcnew CProperties;
        CRentalProperty ^ rental = nullptr;
    
        rental = gcnew CRentalProperty;
        rental->PropertyCode = 737495;
        rental->PropertyType = PropertyTypes::Apartment;
        rental->PropertyCondition = PropertyConditions::Good;
        rental->Bedrooms = 1;
        rental->Bathrooms = 1;
        rental->MonthlyRent = 950.00;
        properties->Add(rental);
    
        rental = gcnew CRentalProperty;
        rental->PropertyCode = 293749;
        rental->PropertyType = PropertyTypes::SingleFamily;
        rental->PropertyCondition = PropertyConditions::Excellent;
        rental->Bedrooms = 5;
        rental->Bathrooms = 3.5;
        rental->MonthlyRent = 2550.75;
        properties->Add(rental);
    
        rental = gcnew CRentalProperty;
        rental->PropertyCode = 224006;
        rental->PropertyType = PropertyTypes::Apartment;
        rental->PropertyCondition = PropertyConditions::Excellent;
        rental->Bedrooms = 2;
        rental->Bathrooms = 1;
        rental->MonthlyRent = 1250.55;
        properties->Add(rental);
    
        rental = gcnew CRentalProperty;
        rental->PropertyCode = 197249;
        rental->PropertyType = PropertyTypes::Townhouse;
        rental->PropertyCondition = PropertyConditions::BadShape;
        rental->Bedrooms = 4;
        rental->Bathrooms = 2.5;
        rental->MonthlyRent = 1750.65;
        properties->Add(rental);
    
        Console::WriteLine(L"<+> Solas Properties Rental <+>");
        Console::WriteLine(L"<->   Properties Listing    <->");
        for(int i = 0; i < properties->Count; i++)
        {
    	Console::WriteLine(L"---------------------------");
    	Console::WriteLine(L"{0}. Property Details",
                            (i+1).ToString());
    	Console::WriteLine(L"Property #:    {0}",
    			properties->Get(i)->PropertyCode);
    	Console::WriteLine(L"Property Type: {0}",
    			properties->Get(i)->PropertyType);
    	Console::WriteLine(L"Condition:     {0}",
    			properties->Get(i)->PropertyCondition);
    	Console::WriteLine(L"Bedrooms:      {0}",
    			properties->Get(i)->Bedrooms);
    	Console::WriteLine(L"Bathrooms:     {0}",
    			properties->Get(i)->Bathrooms);
    	Console::WriteLine(L"Monthly Rent:  {0}",
    			properties->Get(i)->MonthlyRent);
        }
        Console::WriteLine(L"================================");
        return 0;
    }
  11. Execute the application to see the result
     
    <+> Solas Properties Rental <+>
    <->   Properties Listing    <->
    ---------------------------
    1. Property Details
    Property #:    737495
    Property Type: Apartment
    Condition:     Good
    Bedrooms:      1
    Bathrooms:     1
    Monthly Rent:  950
    ---------------------------
    2. Property Details
    Property #:    293749
    Property Type: SingleFamily
    Condition:     Excellent
    Bedrooms:      5
    Bathrooms:     3.5
    Monthly Rent:  2550.75
    ---------------------------
    3. Property Details
    Property #:    224006
    Property Type: Apartment
    Condition:     Excellent
    Bedrooms:      2
    Bathrooms:     1
    Monthly Rent:  1250.55
    ---------------------------
    4. Property Details
    Property #:    197249
    Property Type: Townhouse
    Condition:     BadShape
    Bedrooms:      4
    Bathrooms:     2.5
    Monthly Rent:  1750.65
    ================================
    Press any key to continue . . .
  12. Close the DOS window and return to your programming environment

Inserting an Item

When you call the IList::Add() method, it adds the new item to the end of the list. Sometimes, you will want the new item to be insert somewhere inside the list. To support this operation, the IList interface provides a method named Insert. Its syntax is:

void Insert(int index, Object^ value);

This method takes two arguments. The second argument is the object that will be inserted into the list. The argument must hold a valid value. Because this method takes an Object handle, if your collection is using a different type of item, you may have to cast it to Object. The first argument is the index of the item that will precede the new one.

As mentioned for the Add() method, there are a few things you should know about this operation success or lack of it:

  • If the index argument holds a negative value or a value higher than the allowed number (for example if the collection is an array) of the items (depending on how you implement the method), the new item would not be added, the compiler would not throw an exception, and therefore nothing would let you know that the item was not added. If you want to find out whether the item was formally or actually inserted or not, you must create the functionality yourself
  • If the value argument is not valid, again depending on how you structure your class, either the item would not be inserted or something else would go wrong. Fortunately, if the value argument is of type of a class you created yourself, the compiler would produce an error such as letting you know that the argument is holding a value that is conform to its property or member variable. For example, imagine the value is a CStudent object that has an integer member named age. If you assign a String, such as CStudent::Age = L"Raymond", the error thrown by the compiler would know that it is the CStudent object that is not holding a right value and therefore this object would not even get to the collection class

Practical Learning Practical Learning: Inserting an Item in the Collection

  1. Access the Properties.cpp source file.
    In the Scopes combo box of the Code Editor, select CProperties and, in the Functions combo box, select Insert
  2. Implement the Insert() method as follows:
     
    // This method can be used to insert an item at a 
    // certain position inside the collection
    void CProperties::Insert(int index, Object ^ value)
    {
        if( (counter <= RentalProperties->Length) &&
    	(index < Count) &&
    	(index >= 0) )
        {
            counter++;
    
    	for(int i = Count - 1; i > index; i--)
    		RentalProperties[i] = RentalProperties[i - 1];
    	RentalProperties[index] = value;
        }
    }
  3. Open the Exercise.cpp source file and change it as follows:
     
    #include "RentalProperty.h"
    #include "Properties.h"
    
    using namespace System;
    
    int main()
    {
        CProperties ^ properties = gcnew CProperties;
        CRentalProperty ^ rental = nullptr;
    
        . . . No Change
    	
        rental = gcnew CRentalProperty;
        rental->PropertyCode = 592795;
        rental->PropertyType = PropertyTypes::SingleFamily;
    	rental->PropertyCondition = PropertyConditions::Good;
        rental->Bedrooms = 3;
        rental->Bathrooms = 2.00;
        rental->MonthlyRent = 1870.35;
        properties->Insert(2, rental);
    
        Console::WriteLine(L"<+> Solas Properties Rental <+>");
        Console::WriteLine(L"<->   Properties Listing    <->");
        for(int i = 0; i < properties->Count; i++)
        {
    	Console::WriteLine(L"---------------------------");
    	Console::WriteLine(L"{0}. Property Details",
                            (i+1).ToString());
    	Console::WriteLine(L"Property #:    {0}",
    			properties->Get(i)->PropertyCode);
    	Console::WriteLine(L"Property Type: {0}",
    			properties->Get(i)->PropertyType);
    	Console::WriteLine(L"Condition:     {0}",
    			properties->Get(i)->PropertyCondition);
    	Console::WriteLine(L"Bedrooms:      {0}",
    			properties->Get(i)->Bedrooms);
    	Console::WriteLine(L"Bathrooms:     {0}",
    			properties->Get(i)->Bathrooms);
    	Console::WriteLine(L"Monthly Rent:  {0}",
    			properties->Get(i)->MonthlyRent);
        }
        Console::WriteLine(L"================================");
        return 0;
    }
  4. Execute the application to see the result
     
    <+> Solas Properties Rental <+>
    <->   Properties Listing    <->
    ---------------------------
    1. Property Details
    Property #:    737495
    Property Type: Apartment
    Condition:     Good
    Bedrooms:      1
    Bathrooms:     1
    Monthly Rent:  950
    ---------------------------
    2. Property Details
    Property #:    293749
    Property Type: SingleFamily
    Condition:     Excellent
    Bedrooms:      5
    Bathrooms:     3.5
    Monthly Rent:  2550.75
    ---------------------------
    3. Property Details
    Property #:    592795
    Property Type: SingleFamily
    Condition:     Good
    Bedrooms:      3
    Bathrooms:     2
    Monthly Rent:  1870.35
    ---------------------------
    4. Property Details
    Property #:    224006
    Property Type: Apartment
    Condition:     Excellent
    Bedrooms:      2
    Bathrooms:     1
    Monthly Rent:  1250.55
    ---------------------------
    5. Property Details
    Property #:    197249
    Property Type: Townhouse
    Condition:     BadShape
    Bedrooms:      4
    Bathrooms:     2.5
    Monthly Rent:  1750.65
    ================================
    Press any key to continue . . .
  5. Close the DOS window and return to your programming environment
 

Previous Copyright © 2007-2012 FunctionX Next