Basics of .NET Collections in C#






3.46/5 (32 votes)
This article focuses on managing collections in .NET Framework 2.0.

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
onobjA
andobjB
and callsobjA.Equals(objB)
. It returnstrue
ifobjA
andobjB
arenull
references or both are the same instance, or ifobjA.Equals(objB)
returnstrue
, otherwise it returnsfalse
.int n1 = 2; int n2 = 3; bool result1 = object.Equals(n1, n2); // returns false. // because n1 & n2 are value type // and it will be compared by value. string s1 = "test"; string s2 = "test"; bool result2 = object.Equals(s1, s2); // returns true. s1 & s2 are // reference type, // but Equals(object obj) method of // object class is overridden by // string class. // that's why it returns true because // s1 and s2 are comparing // by their values. object obj1 = new Person(1, "Test1"); object obj2 = new Person(1, "Test1"); bool result3 = object.Equals(obj1, obj2); // returns false. obj1 & obj2 // are reference type, // both are comparing by // reference and both are // different instances but // having same values.
-
object.ReferenceEquals(object objA, object objB)
This method returns
true
ifobjA
is the same instance asobjB
or both havenull
reference, otherwise returnfalse
.int n1 = 2; int n2 = 2; bool result1 = object.ReferenceEquals(n1, n2); // returns false. // because n1 & n2 are // different instances. object obj1 = new Person(1, "Test1"); object obj2 = new Person(1, "Test1"); object obj3 = obj1; bool result2 = object.ReferenceEquals(obj1, obj2); // returns false because // obj1 & obj2 are different instances. bool result3 = object.ReferenceEquals(obj1, obj3); // returns true because // obj1 & obj2 are same instances.
-
-
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 isstring
class, which overridesEquals()
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); // returns true. // because s1 & s2 has same value. object obj1 = new Person(1, "Test1"); object obj2 = new Person(1, "Test1"); object obj3 = obj1; bool result2 = obj1.Equals(obj2); // returns false. // because obj1 & obj2 are different // instances. bool result3 = obj1.Equals(obj3); // returns true. // because obj1 & obj3 are same instances.
-
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 overrideGetHashCode
in your custom types.object obj1 = 4; object obj2 = "Test"; object obj3 = new Person(1, "Test1"); int result1 = obj1.GetHashCode(); // returns 4. int result2 = obj2.GetHashCode(); // returns -354185577. int result3 = obj3.GetHashCode(); // returns 2418355.
-
GetType()
It returns the
Type
object of current instance.Type
is the basis for using reflection in .NET. Use the members ofType
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(); // returns System.Int32 string type2 = obj2.GetType().ToString(); // returns System.String. string type3 = obj3.GetType().ToString(); // returns DotNetCollections. // CollectionExp.Person.
-
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 ofDouble
returns thestring
representation of the value that the object has.object obj1 = 4; object obj2 = "Test"; object obj3 = new Person(1, "Test1"); string s1 = obj1.ToString(); // returns 4 string s2 = obj2.ToString(); // returns Test string s3 = obj3.ToString(); // returns DotNetCollections. // CollectionExp.Person.
-
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
.// Array List ArrayList sourceList = new ArrayList(); sourceList.Add(10); sourceList.Add(20); sourceList.Add(30); int count = sourceList.Count; // count = 3.
IsSynchronized
It returns
true
if access to theICollection
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 theICollection
object to any array, starting at a particularArray
index. If .NET is unable to cast source type to destination, then it throwsArrayTypeMismatchException
exception.// Copy int array to other int array int[] sourceIDs = new int[] { 1, 2, 3, 4, 5 }; int[] destinationIDs = new int[sourceIDs.Length]; sourceIDs.CopyTo(destinationIDs, 0); // destinationIDs = 1, 2, 3, 4, 5 // Copy array list items to int array. // But each item in array list has int type 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); // start copy on index 2. // destinationList = 1, 5, 10, 20, 30
-
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
ifIList
has fixed size.ArrayList arrayList = new ArrayList(); bool isFixedSize = arrayList.IsFixedSize; // false, because ArrayList // is not fixed size list
IsReadOnly
It returns
true
ifIList
is read only.ArrayList arrayList = new ArrayList(); arrayList.Add(1); arrayList.Add(2); arrayList.Add(3); bool readOnly = arrayList.IsReadOnly; // false, because default array // list is not readonly. // create readonly list from existing list ArrayList readOnlyList = ArrayList.ReadOnly(arrayList); bool isNewListReadOnly = readOnlyList.IsReadOnly; // true. now user can't // modify this list
-
Methods
-
Add(object value)
It adds the item into the
IList
.ArrayList arrayList = new ArrayList(); arrayList.Add(1); // Add First Item arrayList.Add(2); // Add Second Item arrayList.Add(3); // Add Third Item
-
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; // 3 arrayList.Clear(); itemsCount = arrayList.Count; // 0
-
Contains(object value)
It returns
true
ifIList
contain a specific value. This method uses theEquals
andCompareTo
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); // true bool result2 = arrayList.Contains(person2); // false
-
IndexOf(object value)
It returns the index of a specific item in the
IList
. This method also uses theEquals
andCompareTo
methods to determine whether an item exists.// Populate Array list ArrayList arrayList = new ArrayList(); arrayList.Add(new Person(1, "test1")); arrayList.Add(new Person(2, "test2")); arrayList.Add(new Person(3, "test3")); // create new object Person person3 = new Person(3, "test3"); Person person4 = new Person(4, "test4"); int result1 = arrayList.IndexOf(person3); // 2, int result2 = arrayList.IndexOf(person4); // -1. because it does not exist // in list
-
Insert(int index, object value)
It inserts an item to the
IList
at specific index. If index equals the number of items in theIList
, then value is appended to the end, but if index greater then the number of items in theIList
or less then zero, then it throwsArgumentOutOfRangeException
exception. If you try to insert item in the read-only or fixed sizeIList
then it throwsNotSupportedException
exception.ArrayList arrayList = new ArrayList(); arrayList.Add(new Person(1, "test1")); arrayList.Add(new Person(2, "test2")); arrayList.Add(new Person(3, "test3")); // create new object Person person =new Person(4, "test4"); // insert item at index 2. 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 sizeIList
, then it throwsNotSupportedException
.ArrayList arrayList = new ArrayList(); arrayList.Add(new Person(1, "test1")); arrayList.Add(new Person(2, "test2")); arrayList.Add(new Person(3, "test3")); // Create person Person person = new Person(2, "test2"); arrayList.Remove(person); // it will remove 2nd item. it will call // Equals method to object to find in list.
-
RemoveAt(int index)
It removes an item at the specified index. It throws
ArgumentOutOfRangeException
exception for invalid index in list and throwsNotSupportedException
exception for read only and fixed sizeIList
.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); // remove item at index 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
ifIDictionary
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; // false
IsReadOnly
It returns
true
ifIDictionary
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 theIDictionary
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); // 3, 2, 1
Values
It returns
ICollection
object containing values of theIDictionary
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); //item#1, item#2, item#3
-
Methods
-
Add(object key, object value)
Adds an element with the specified
key
andvalue
into theIDictionary
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(); // it removes all item from the list.
-
Contains(object key)
It returns
true
ifIDictionary
object contains an element with the specifiedkey
.Hashtable hashList = new Hashtable(); hashList.Add(1, "item#1"); hashList.Add(2, "item#2"); hashList.Add(3, "item#3"); bool result = hashList.Contains(1); // true
-
GetEnumerator()
It returns an
IDictionaryEnumerator
object for theIDictionary
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 theIDictionary
object.Hashtable hashList = new Hashtable(); hashList.Add(1, "item#1"); hashList.Add(2, "item#2"); hashList.Add(3, "item#3"); hashList.Remove(2); // remove item which has 2 key
-
References
- http://msdn.microsoft.com/en-us/library/system.object(VS.71).aspx
- http://msdn.microsoft.com/en-us/library/system.collections.icollection.aspx
- http://msdn.microsoft.com/en-us/library/system.collections.ilist.aspx
- http://msdn.microsoft.com/en-us/library/system.collections.idictionary_members(VS.80).aspx
History
- 10th December, 2008: Initial post