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+

Collection Interfaces

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.

IDictionary.Keys and IDictionary.Values

Dictionaries can be thought of as two related collections; one collection of keys and one collection of values. This concept can be realised by extracting either group as a collection in its own right. The Keys and Values properties provide access to these two sets of values, returning either as a collection.

The type of collection returned is not defined and may vary according to the dictionary being interrogated. However, the returned collections will always inherit the ICollection interface. As such, the return value can be declared using the ICollection interface name and the underlying type can be safely ignored.

The following example uses both of these properties to loop through each key and value independently.

Hashtable users = new Hashtable();

// Add some users
users.Add("andyb", "Andrew Brown");
users.Add("alexg", "Alex Green");
users.Add("adrienneb", "Adrienne Black");

// Extract the keys and values
ICollection keys = users.Keys;
ICollection values = users.Values;

// Loop through each key and value
foreach(object key in keys)

foreach(object value in values)


Adrienne Black
Alex Green
Andrew Brown



In the above examples, the foreach command has been used to loop through the items in a collection. This is possible because the ICollection interface supports the IEnumerable interface.

24 April 2007