BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 1.1+

The SortedList Collection

The thirty-ninth part of the C# Fundamentals tutorial describes the use of the SortedList class. This dictionary collection provides a hybrid of the Hashtable and Array types; each entry being a key / value pair sorted according to the key's contents.

SortedList Capacity

As previously mentioned, when a SortedList is created, it has a predetermined size. The size may be specified directly in the constructor, indirectly due to the manner in which the SortedList is initialised or as the default size, which varies according to the version of the .NET framework in use.

As items are added to the SortedList and the capacity is exceeded, the capacity automatically doubles to allow the new additions. Each time this occurs, there is an overhead in allocation of new memory and copying of SortedList data. It is advisable, therefore, to set the capacity of an SortedList when the maximum size of the collection is known and when the number of entries that may be required is reasonably stable.

The capacity of an SortedList can be obtained and modified using the Capacity property. This property holds an integer.

SortedList myCollection = new SortedList();

int capacity = myCollection.Capacity;
Console.WriteLine("Default capacity is {0} items", capacity);

myCollection.Capacity = 25;
capacity = myCollection.Capacity;
Console.WriteLine("New capacity is {0} items", capacity);

/* OUTPUT

Default capacity is 16 items
New capacity is 25 items

*/

Once a SortedList has been fully populated and no further items will be added, the memory allocated to the unused part of the dictionary can be reclaimed. The TrimToSize method sets the capacity of the collection to match the current contents.

SortedList myCollection = new SortedList();

myCollection.Add("One", 1);
myCollection.Add("Two", 2);
myCollection.Add("Three", 3);
myCollection.Add("Four", 4);
myCollection.Add("Five", 5);

int capacity = myCollection.Capacity;
Console.WriteLine("Initial capacity is {0} items", capacity);

myCollection.TrimToSize();
capacity = myCollection.Capacity;
Console.WriteLine("New capacity is {0} items", capacity);

/* OUTPUT

Initial capacity is 16 items
New capacity is 5 items

*/

Creating a Thread-Safe SortedList Wrapper

In the earlier article discussing collection interfaces, the concept of a thread-safe synchronised collection was described. In order to create a thread-safe SortedList, a synchronised wrapper dictionary is generated using the static Synchronized method.

SortedList myDictionary = new SortedList();
SortedList myThreadSafe = SortedList.Synchronized(myDictionary);
Console.WriteLine(myThreadSafe.IsSynchronized);	        // Outputs "True"
29 May 2007