< C++ .NET Arrays & Collections 11 | Main | C++ .NET Arrays & Collections 13 >


 

 

More On Arrays and Collections 12

 

 

What we have in this page?

 

  1. The StringCollection Class

------------Next--------------------

  1. Supplementary Notes: ^ (Handle to Object on Managed Heap), gcnew and for each, in

 

 

The StringCollection Class

 

The StringCollection class, defined in the System::Collections::Specialized namespace represents a collection of strings. The syntax is shown below.

[SerializableAttribute]

public ref class StringCollection : IList, ICollection, IEnumerable

StringCollection lets you access elements by index, and it lets you add, remove, and insert items. Because the StringCollection class implements the ICollection, IEnumerable, and IList interfaces, the class implements the methods associated with those interfaces, so it provides a lot of functionality that you’ve already met, such as Clear, Count, Contains, and CopyTo. In the following brief exercise, you’ll create a StringCollection and see how to use it. StringCollection accepts a null reference (Nothing in Visual Basic) as a valid value and allows duplicate elements. String comparisons are case-sensitive. Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.

 

1.        Open Visual C++/Studio, and create a new CLR Console Application project named StringCollection.

 

Creating a new C++ .NET CLR Console Application project named StringCollection

 

 

2.        Open the StringCollection.cpp source file and try the following long example that demonstrates several of the properties and methods of StringCollection.

// StringCollection.cpp : main project file.

 

#include "stdafx.h"

#using <System.dll>

 

using namespace System;

using namespace System::Collections;

using namespace System::Collections::Specialized;

 

// prototypes...

void PrintValues1(StringCollection^ myCol);

void PrintValues2(StringCollection^ myCol);

void PrintValues3(StringCollection^ myCol);

 

int main(array<System::String ^> ^args)

{

      Console::WriteLine("StringCollection Class Properties and Methods");

      Console::WriteLine();

      // Create and initializes a new StringCollection.

      StringCollection^ myCol = gcnew StringCollection;

      // Add a range of elements from an array to the end of the StringCollection.

      array<String^>^myArr = {"RED","orange","yellow","RED","green","blue","RED","indigo","violet","RED"};

      myCol->AddRange(myArr);

      // Display the contents of the collection using for each. This is the preferred method.

      Console::WriteLine("Displays the elements using for each:");

      PrintValues1(myCol);

      // Display the contents of the collection using the enumerator.

      Console::WriteLine("Displays the elements using the IEnumerator:");

      PrintValues2(myCol);

      // Display the contents of the collection using the Count and Item properties.

      Console::WriteLine( "Displays the elements using the Count and Item properties:" );

      PrintValues3(myCol);

      // Add one element to the end of the StringCollection and insert another at index 3.

      myCol->Add("* white");

      myCol->Insert(3, "* gray");

      Console::WriteLine("After adding \"* white\" to the end and inserting \"* gray\" at index 3:");

      PrintValues1( myCol );

      // Remove one element from the StringCollection.

      myCol->Remove("yellow");

      Console::WriteLine("After removing \"yellow\":");

      PrintValues1(myCol);

      // Remove all occurrences of a value from the StringCollection.

      int i = myCol->IndexOf("RED");

      while (i > -1)

      {

         myCol->RemoveAt(i);

         i = myCol->IndexOf("RED");

      }

      // Verify that all occurrences of "RED" are gone.

      if (myCol->Contains("RED"))

         Console::WriteLine("*** The collection still contains \"RED\".");

      Console::WriteLine("After removing all occurrences of \"RED\":");

      PrintValues1(myCol);

      // Copy the collection to a new array starting at index 0.

      array<String^>^myArr2 = gcnew array<String^>(myCol->Count);

      myCol->CopyTo(myArr2, 0);

      Console::WriteLine("The new array contains:");

      for (i = 0; i < myArr2->Length; i++)

      {

          Console::WriteLine("   [{0}] {1}", i, myArr2[ i ]);

      }

      Console::WriteLine();

      // Clears the entire collection.

      myCol->Clear();

      Console::WriteLine("After clearing the collection:");

      PrintValues1(myCol);

    return 0;

}

 

// Uses the for each statement which hides the complexity

// of the enumerator. The for each statement is the preferred

// way of enumerating the contents of a collection.

void PrintValues1(StringCollection^ myCol)

{

   for each (Object^ obj in myCol)

     Console::WriteLine("   {0}", obj);

   Console::WriteLine();

}

 

// Uses the enumerator.

void PrintValues2(StringCollection^ myCol)

{

   StringEnumerator^ myEnumerator = myCol->GetEnumerator();

   while (myEnumerator->MoveNext())

      Console::WriteLine("   {0}", myEnumerator->Current);

   Console::WriteLine();

}

 

// Uses the Count and Item properties.

void PrintValues3(StringCollection^ myCol)

{

   for (int i = 0; i < myCol->Count; i++)

      Console::WriteLine("   {0}", myCol[ i ]);

   Console::WriteLine();

}

 

Sample Output:

StringCollection Class Properties and Methods

 

Displays the elements using for each:

   RED

   orange

   yellow

   RED

   green

   blue

   RED

   indigo

   violet

   RED

 

Displays the elements using the IEnumerator:

   RED

   orange

   yellow

   RED

   green

   blue

   RED

   indigo

   violet

   RED

 

Displays the elements using the Count and Item properties:

   RED

   orange

   yellow

   RED

   green

   blue

   RED

   indigo

   violet

   RED

 

After adding "* white" to the end and inserting "* gray" at index 3:

   RED

   orange

   yellow

   * gray

   RED

   green

   blue

   RED

   indigo

   violet

   RED

   * white

 

After removing "yellow":

   RED

   orange

   * gray

   RED

   green

   blue

   RED

   indigo

   violet

   RED

   * white

 

After removing all occurrences of "RED":

   orange

   * gray

   green

   blue

   indigo

   violet

   * white

 

The new array contains:

   [0] orange

   [1] * gray

   [2] green

   [3] blue

   [4] indigo

   [5] violet

   [6] * white

 

After clearing the collection:

 

Press any key to continue . . .

 

 

 

 

 

Unlike ArrayList and SortedList, StringCollection objects are created with no initial capacity and simply grow as more items are added. Because StringCollection implements the ICollection, IList, and IEnumerable interfaces, it supports much of the same functionality as the other classes we’ve discussed, including the ability to use enumerators. The following tables list the members exposed by the StringCollection type.

 

Public Constructors

Symbol

Public method

Name

Description

StringCollection

Initializes a new instance of the StringCollection class.

 

Table 11

 

Public Properties

Symbol

Public property

Name

Description

Count

Gets the number of strings contained in the StringCollection.

IsReadOnly

Gets a value indicating whether the StringCollection is read-only.

IsSynchronized

Gets a value indicating whether access to the StringCollection is synchronized (thread safe).

Item

Gets or sets the element at the specified index.

SyncRoot

Gets an object that can be used to synchronize access to the StringCollection.

 

Table 12

 

Public Methods

Symbol

Public method

Name

Description

Add

Adds a string to the end of the StringCollection.

AddRange

Copies the elements of a string array to the end of the StringCollection.

Clear

Removes all the strings from the StringCollection.

Contains

Determines whether the specified string is in the StringCollection.

CopyTo

Copies the entire StringCollection values to a one-dimensional array of strings, starting at the specified index of the target array.

Equals

Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)

GetEnumerator

Returns a StringEnumerator that iterates through the StringCollection.

GetHashCode

Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)

GetType

Gets the Type of the current instance. (Inherited from Object.)

IndexOf

Searches for the specified string and returns the zero-based index of the first occurrence within the StringCollection.

Insert

Inserts a string into the StringCollection at the specified index.

ReferenceEquals

Determines whether the specified Object instances are the same instance. (Inherited from Object.)

Remove

Removes the first occurrence of a specific string from the StringCollection.

RemoveAt

Removes the string at the specified index of the StringCollection.

ToString

Returns a String that represents the current Object. (Inherited from Object.)

 

Table 13

 

Protected Methods

Symbol

Protected method

Name

Description

Finalize

Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)

MemberwiseClone

Creates a shallow copy of the current Object. (Inherited from Object.)

 

Table 14

 

Explicit Interface Implementations

Symbol

Explicit interface implementation

Name

Description

System.Collections.ICollection.CopyTo

Copies the entire StringCollection to a compatible one-dimensional Array, starting at the specified index of the target array.

System.Collections.IEnumerable.GetEnumerator

Returns a IEnumerator that iterates through the StringCollection.

System.Collections.IList.Add

Adds an object to the end of the StringCollection.

System.Collections.IList.Contains

Determines whether an element is in the StringCollection.

System.Collections.IList.IndexOf

Searches for the specified Object and returns the zero-based index of the first occurrence within the entire StringCollection.

System.Collections.IList.Insert

Inserts an element into the StringCollection at the specified index.

System.Collections.IList.Remove

Removes the first occurrence of a specific object from the StringCollection.

System.Collections.IList.IsFixedSize

Gets a value indicating whether the StringCollection object has a fixed size.

System.Collections.IList.IsReadOnly

Gets a value indicating whether the StringCollection object is read-only.

System.Collections.IList.Item

Gets or sets the element at the specified index.

 

Table 15

 

Note: You may find that in C++ .Net the dot (.) is replaced by scope operator (::).

 

 

 

 

 Part 1 | Part 2 | part 3 | Part 4 | Part 5 | Part 6

 


 

< C++ .NET Arrays & Collections 11 | Main | C++ .NET Arrays & Collections 13 >