Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Basics of .NET Collections in C#

3.46/5 (32 votes)
10 Dec 2008CPOL6 min read 328K   2.6K  
This article focuses on managing collections in .NET Framework 2.0.
Image 1

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.

Class Giagram

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.

  1. Static Methods

    • C#
      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.

      C#
      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.
      
    • C#
      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.

      C#
      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.
      
  2. Methods

    • C#
      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.

      C#
      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.
      
    • C#
      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.

      C#
      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.
      
    • C#
      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.

      C#
      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.
      
    • C#
      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.

      C#
      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.

  1. Methods

    • C#
      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.

      C#
      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.

  1. Properties

    • Count

      It returns the number of elements contain by ICollection.

      C#
      // 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 the ICollection is synchronized.

    • SyncRoot

      It returns an object that can be used to synchronize access to the ICollection.

      C#
      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);
      }
      
  2. Methods

    • C#
      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.

      C#
      // 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.

  1. Properties

    • IsFixedSize

      It returns true if IList has fixed size.

      C#
      ArrayList arrayList = new ArrayList();
      bool isFixedSize = arrayList.IsFixedSize; // false, because ArrayList
                                                // is not fixed size list
      
    • IsReadOnly

      It returns true if IList is read only.

      C#
      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
      
  2. Methods

    • C#
      Add(object value) 

      It adds the item into the IList.

      C#
      ArrayList arrayList = new ArrayList();
      arrayList.Add(1); // Add First Item
      arrayList.Add(2); // Add Second Item
      arrayList.Add(3); // Add Third Item
      
    • C#
      Clear() 

      It removes the all items from the IList.

      C#
      ArrayList arrayList = new ArrayList();
      arrayList.Add(1);
      arrayList.Add(2);
      arrayList.Add(3);
      
      int itemsCount = arrayList.Count; // 3
      
      arrayList.Clear();
      itemsCount = arrayList.Count; // 0
      
    • C#
      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.

      C#
      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
      
    • C#
      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.

      C#
      // 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
      
    • C#
      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.

      C#
      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);
      
    • C#
      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.

      C#
      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.
      
    • C#
      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.

      C#
      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.

  1. Properties

    • IsFixedSize

      It returns true if IDictionary object has a fixed size.

      C#
      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 if IDictionary object is read only.

      C#
      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.

      C#
      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 the IDictionary object.

      C#
      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
      
  2. Methods

    • C#
      Add(object key, object value) 

      Adds an element with the specified key and value into the IDictionary object.

      C#
      Hashtable hashList = new Hashtable();
      hashList.Add(1, "item#1");
      hashList.Add(2, "item#2");
      hashList.Add(3, "item#3");
      
    • C#
      Clear() 

      It removes all elements from the IDictionary object.

      C#
      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.
      
    • C#
      Contains(object key) 

      It returns true if IDictionary object contains an element with the specified key.

      C#
      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
      
    • C#
      GetEnumerator() 

      It returns an IDictionaryEnumerator object for the IDictionary object.

      C#
      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);
      
    • C#
      Remove(object key) 

      It removes the element with the specified key from the IDictionary object.

      C#
      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

History

  • 10th December, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)