BlackWaspTM
.NET Framework
.NET 1.1+

Collection Interfaces (2)

The thirty-sixth part of the C# Fundamentals tutorial introduces the use of collections in C#. A collection is similar to an array in that it contains a group of objects. However, the use of varying types of collection provide for more functionality.

ICollection.CopyTo

The CopyTo method allows you to copy each item from a collection into an array. The basic CopyTo method accepts two parameters. The first is the array to fill. The second is an integer representing the index of the first item in the array to copy to. Each item from the collection is placed in subsequent indexes of the array.

In the example below, the collection is copied to index zero of the array, which is the first element. The example demonstrates the use of CopyTo for the ArrayList, a commonly used collection that provides a one-dimensional dynamic array structure. The ArrayList is found in the System.Collections namespace so to execute the example, add using System.Collections; to the source code.

ArrayList names = new ArrayList();

// Add some names
names.Add("Andrew");
names.Add("Alex");
names.Add("Adrienne");

// Copy the collection into a new array of strings
string[] namesArray = new string[3];
names.CopyTo(namesArray, 0);

foreach(string name in namesArray)
{
    Console.WriteLine(name);
}

/* OUTPUT

Andrew
Alex
Adrienne

*/

NB: Strings are used throughout this article within the examples. These are used for ease of demonstration only and could be replaced with any type of object.

ICollection.Count

The Count property returns the number of items that exist within a collection as an integer value.

ArrayList names = new ArrayList();

// Add some names
names.Add("Andrew");
names.Add("Alex");
names.Add("Adrienne");

Console.WriteLine(names.Count);                 // Outputs "3"

ICollection.IsSynchronized

When writing programs that are multi-threaded, it is possible that more than one thread of execution could access a collection simultaneously. If many threads are reading from and writing to a collection, unexpected problems could occur. To alleviate this problem collections may be synchronised. A synchronised (or synchronized) collection allows writing from multiple threads.

To determine if a collection is synchronised, you can check the Boolean IsSynchronized property. By default, collections are not synchronised.

ArrayList names = new ArrayList();

Console.WriteLine(names.IsSynchronized);        // Outputs "False"
24 April 2007