Introduction
This article focuses on managing collections in .NET Framework 2.0. Collection represents a set of objects that you can access by stepping through each element in turn. The .NET Framework provides specialized classes for managing collection and these classes have rich capability for enhancing your programming experience through better performance and easy maintenance.
Object
class is the base class of every type in .NET. All the collections implement IEnumerable
interface that is extended by ICollection
interface. IDictionary
and IList
are also interfaces for collection which are derived from ICollection
as shown in the diagram.
System.Object
Object
class is the base class of every type. All other types directly or indirectly derive from object
class. Because of its lofty position, a .NET developer should have a good knowledge of the object
class and its members.
Static Methods
-
object.Equals(object objA, object objB)
This method does some testing for null
on objA
and objB
and calls objA.Equals(objB)
. It returns true
if objA
and objB
are null
references or both are the same instance, or if objA.Equals(objB)
returns true
, otherwise it returns false
.
int n1 = 2;
int n2 = 3;
bool result1 = object.Equals(n1, n2);
string s1 = "test";
string s2 = "test";
bool result2 = object.Equals(s1, s2);
object obj1 = new Person(1, "Test1");
object obj2 = new Person(1, "Test1");
bool result3 = object.Equals(obj1, obj2);
-
object.ReferenceEquals(object objA, object objB)
This method returns true
if objA
is the same instance as objB
or both have null
reference, otherwise return false
.
int n1 = 2;
int n2 = 2;
bool result1 = object.ReferenceEquals(n1, n2);
object obj1 = new Person(1, "Test1");
object obj2 = new Person(1, "Test1");
object obj3 = obj1;
bool result2 = object.ReferenceEquals(obj1, obj2);
bool result3 = object.ReferenceEquals(obj1, obj3);
Methods
-
Equals(object obj)
The default implementation of Equals()
supports reference equality only, but derived class can override this method to support value equality. An example is string
class, which overrides Equals()
to ensure that the two strings are compared by the value of their strings. A common operation, especially for searching or sorting in collections is testing two objects for equality.
string s1 = "Test";
string s2 = "Test";
bool result1 = s1.Equals(s2);
object obj1 = new Person(1, "Test1");
object obj2 = new Person(1, "Test1");
object obj3 = obj1;
bool result2 = obj1.Equals(obj2);
bool result3 = obj1.Equals(obj3);
-
GetHashCode()
It returns the hash code for the current object. This method also serves as a hash function for a particular type. It is suitable for use in hashing algorithms and data structures like a hash table. This method can be overridden by the derive
class. Object.GetHashCode()
returns the same hash code for the same instance, but it is not necessary that it will return a different hash code for two different instances or the same hash code for two instances which have the same values. Different versions of the .NET Framework might also generate different hash codes for the same instance.
Default hash code returned by the GetHashCode()
method has no guarantee to be unique, you should override GetHashCode
in your custom types.
object obj1 = 4;
object obj2 = "Test";
object obj3 = new Person(1, "Test1");
int result1 = obj1.GetHashCode();
int result2 = obj2.GetHashCode();
int result3 = obj3.GetHashCode();
-
GetType()
It returns the Type
object of current instance. Type
is the basis for using reflection in .NET. Use the members of Type
to get information about a type declaration, such as the constructors, methods, fields, properties, and events of a class, as well as the module and the assembly in which the class is deployed.
object obj1 = 4;
object obj2 = "Test";
object obj3 = new Person(1, "Test1");
string type1 = obj1.GetType().ToString();
string type2 = obj2.GetType().ToString();
string type3 = obj3.GetType().ToString();
-
ToString()
It returns the human readable string of the object that is culture specific. The default implementation returns the runtime type of the object. The derive class can override this method for returning meaningful value of the type. For example, the ToString()
method of Double
returns the string
representation of the value that the object has.
object obj1 = 4;
object obj2 = "Test";
object obj3 = new Person(1, "Test1");
string s1 = obj1.ToString();
string s2 = obj2.ToString();
string s3 = obj3.ToString();
System.Collections.IEnumerable
It exposes the enumerator, which provides a collection like behavior to user defined classes.
Methods
-
GetEnumerator()
It returns the enumerator object that can be used to iterate through the collection. It allows using the foreach
statement. Enumerators only allow reading the data in the collection.
Array array = new int[] { 12, 24, 26, 35, 40, 59 };
IEnumerator iEnum = array.GetEnumerator();
string msg = "";
while (iEnum.MoveNext())
{
int n = (int)iEnum.Current;
msg += n.ToString() + "\n";
}
MessageBox.Show(msg);
System.Collections.ICollection
ICollection
interface specifies a method for getting the size of collection, creating enumerators on a collection and managing synchronized access to all non-generic collections. It is a base interface for classes in the System.Collections
namespace.
Properties
Count
It returns the number of elements contain by ICollection
.
ArrayList sourceList = new ArrayList();
sourceList.Add(10);
sourceList.Add(20);
sourceList.Add(30);
int count = sourceList.Count;
IsSynchronized
It returns true
if access to the ICollection
is synchronized.
SyncRoot
It returns an object that can be used to synchronize access to the ICollection
.
ArrayList sourceList = new ArrayList();
sourceList.Add(10);
sourceList.Add(20);
sourceList.Add(30);
lock (sourceList.SyncRoot)
{
string list = string.Empty;
foreach (object value in sourceList)
{
if (list.Length > 0)
list += ", ";
list += value.ToString();
}
MessageBox.Show(list);
}
Methods
-
CopyTo(Array array, int index)
CopyTo()
method copies the elements of the ICollection
object to any array, starting at a particular Array
index. If .NET is unable to cast source type to destination, then it throws ArrayTypeMismatchException
exception.
int[] sourceIDs = new int[] { 1, 2, 3, 4, 5 };
int[] destinationIDs = new int[sourceIDs.Length];
sourceIDs.CopyTo(destinationIDs, 0);
ArrayList sourceList = new ArrayList();
sourceList.Add(10);
sourceList.Add(20);
sourceList.Add(30);
int[] destinationList = new int[5];
destinationList[0] = 1;
destinationList[1] = 5;
sourceList.CopyTo(destinationList, 2);
System.Collections.IList
IList
interface represents the collection of objects that can be individually accessed by index. IList
interface represents the collection of objects that can be individually accessed by index. The implementation of IList
falls into three categories: read-only, fixed-size, and variable-size. A read only IList
cannot be modified. A fixed size IList
does not allow the addition or removal of elements, but it allows the modification of the existing elements. A variables size IList
allows the addition, removal, and modification of elements.
Properties
IsFixedSize
It returns true
if IList
has fixed size.
ArrayList arrayList = new ArrayList();
bool isFixedSize = arrayList.IsFixedSize;
IsReadOnly
It returns true
if IList
is read only.
ArrayList arrayList = new ArrayList();
arrayList.Add(1);
arrayList.Add(2);
arrayList.Add(3);
bool readOnly = arrayList.IsReadOnly;
ArrayList readOnlyList = ArrayList.ReadOnly(arrayList);
bool isNewListReadOnly = readOnlyList.IsReadOnly;
Methods
-
Add(object value)
It adds the item into the IList
.
ArrayList arrayList = new ArrayList();
arrayList.Add(1);
arrayList.Add(2);
arrayList.Add(3);
-
Clear()
It removes the all items from the IList
.
ArrayList arrayList = new ArrayList();
arrayList.Add(1);
arrayList.Add(2);
arrayList.Add(3);
int itemsCount = arrayList.Count;
arrayList.Clear();
itemsCount = arrayList.Count;
-
Contains(object value)
It returns true
if IList
contain a specific value. This method uses the Equals
and CompareTo
methods to determine whether an item exists.
ArrayList arrayList = new ArrayList();
arrayList.Add(new Person(1,"test"));
Person person1 = new Person(1, "test");
Person person2 = new Person(2, "test2");
bool result1 = arrayList.Contains(person1);
bool result2 = arrayList.Contains(person2);
-
IndexOf(object value)
It returns the index of a specific item in the IList
. This method also uses the Equals
and CompareTo
methods to determine whether an item exists.
ArrayList arrayList = new ArrayList();
arrayList.Add(new Person(1, "test1"));
arrayList.Add(new Person(2, "test2"));
arrayList.Add(new Person(3, "test3"));
Person person3 = new Person(3, "test3");
Person person4 = new Person(4, "test4");
int result1 = arrayList.IndexOf(person3);
int result2 = arrayList.IndexOf(person4);
-
Insert(int index, object value)
It inserts an item to the IList
at specific index. If index equals the number of items in the IList
, then value is appended to the end, but if index greater then the number of items in the IList
or less then zero, then it throws ArgumentOutOfRangeException
exception. If you try to insert item in the read-only or fixed size IList
then it throws NotSupportedException
exception.
ArrayList arrayList = new ArrayList();
arrayList.Add(new Person(1, "test1"));
arrayList.Add(new Person(2, "test2"));
arrayList.Add(new Person(3, "test3"));
Person person =new Person(4, "test4");
arrayList.Insert(2, person);
-
Remove(object value)
It removes the first occurrence of a specific object from the IList
. If you try to remove value from read only or fixed size IList
, then it throws NotSupportedException
.
ArrayList arrayList = new ArrayList();
arrayList.Add(new Person(1, "test1"));
arrayList.Add(new Person(2, "test2"));
arrayList.Add(new Person(3, "test3"));
Person person = new Person(2, "test2");
arrayList.Remove(person);
-
RemoveAt(int index)
It removes an item at the specified index. It throws ArgumentOutOfRangeException
exception for invalid index in list and throws NotSupportedException
exception for read only and fixed size IList
.
ArrayList arrayList = new ArrayList();
arrayList.Add(new Person(1, "test1"));
arrayList.Add(new Person(2, "test2"));
arrayList.Add(new Person(3, "test3"));
arrayList.RemoveAt(1);
System.Collections.IDictionary
It represents a collection of key/value pairs. IDictionary
interface is implemented by classes that supports collections of associated keys and values. Each element in a key/value pair is stored in a DictionaryEntry
object. It allows the contained keys and values to be enumerated, but it does not imply any particular sort order.
Properties
IsFixedSize
It returns true
if IDictionary
object has a fixed size.
Hashtable hashList = new Hashtable();
hashList.Add(1, "item#1");
hashList.Add(2, "item#2");
hashList.Add(3, "item#3");
bool result = hashList.IsFixedSize;
IsReadOnly
It returns true
if IDictionary
object is read only.
Hashtable hashList = new Hashtable();
hashList.Add(1, "item#1");
hashList.Add(2, "item#2");
hashList.Add(3, "item#3");
bool result = hashList.IsReadOnly;
Keys
It returns ICollection
object containing keys of the IDictionary
object.
Hashtable hashList = new Hashtable();
hashList.Add(1, "item#1");
hashList.Add(2, "item#2");
hashList.Add(3, "item#3");
ICollection keys = hashList.Keys;
string[] strKeys = new string[keys.Count];
int index =0;
foreach (int key in keys)
{
strKeys[index++] = key.ToString();
}
string keysList = string.Join(", ",strKeys);
Values
It returns ICollection
object containing values of the IDictionary
object.
Hashtable hashList = new Hashtable();
hashList.Add(1, "item#1");
hashList.Add(2, "item#2");
hashList.Add(3, "item#3");
ICollection values = hashList.Values;
string[] strValues = new string[values.Count];
int index = 0;
foreach (string value in values)
{
strValues[index++] = value;
}
string valueList = string.Join(", ", strValues);
Methods
-
Add(object key, object value)
Adds an element with the specified key
and value
into the IDictionary
object.
Hashtable hashList = new Hashtable();
hashList.Add(1, "item#1");
hashList.Add(2, "item#2");
hashList.Add(3, "item#3");
-
Clear()
It removes all elements from the IDictionary
object.
Hashtable hashList = new Hashtable();
hashList.Add(1, "item#1");
hashList.Add(2, "item#2");
hashList.Add(3, "item#3");
hashList.Clear();
-
Contains(object key)
It returns true
if IDictionary
object contains an element with the specified key
.
Hashtable hashList = new Hashtable();
hashList.Add(1, "item#1");
hashList.Add(2, "item#2");
hashList.Add(3, "item#3");
bool result = hashList.Contains(1);
-
GetEnumerator()
It returns an IDictionaryEnumerator
object for the IDictionary
object.
Hashtable hashList = new Hashtable();
hashList.Add(1, "item#1");
hashList.Add(2, "item#2");
hashList.Add(3, "item#3");
IDictionaryEnumerator dicEnum = hashList.GetEnumerator();
string items = string.Empty;
while (dicEnum.MoveNext())
{
items += string.Format("{0} : {1}\n", dicEnum.Key, dicEnum.Value);
}
MessageBox.Show(items);
-
Remove(object key)
It removes the element with the specified key
from the IDictionary
object.
Hashtable hashList = new Hashtable();
hashList.Add(1, "item#1");
hashList.Add(2, "item#2");
hashList.Add(3, "item#3");
hashList.Remove(2);
References
History
- 10th December, 2008: Initial post