C# | Collection Class

Collection<T> Class provides the base class for a generic collection. Here T is the type of elements in the collection. This class comes under the System.Collections.ObjectModel namespace.

Characteristics:

  • The Collection<T> class can be used immediately by creating an instance of one of its constructed types.
  • The Collection<T> class provides protected methods that can be used to customize its behavior when adding and removing items, clearing the collection, or setting the value of an existing item.
  • Most Collection<T> objects can be modified. However, a Collection object that is initialized with a read-only IList<T> object cannot be modified.
  • Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.
  • Collection<T> accepts null as a valid value for reference types and allows duplicate elements.

Constructors

Constructor Description
Collection<T>() Initializes a new instance of the Collection<T> class that is empty.
Collection<T>(IList<T>) Initializes a new instance of the Collection<T> class as a wrapper for the specified list.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to create a Collection
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a collection of ints
        Collection<int> myColl = new Collection<int>();
  
        // Adding elements in Collection myColl
        myColl.Add(2);
        myColl.Add(3);
        myColl.Add(4);
        myColl.Add(5);
  
        // Displaying the elements in myColl
        foreach(int i in myColl)
        {
            Console.WriteLine(i);
        }
    }
}

chevron_right


Output:

2
3
4
5

Properties

Property Description
Count Gets the number of elements actually contained in the Collection<T>.
Items Gets a IList<T> wrapper around the Collection<T>.
Item[Int32] Gets or sets the element at the specified index.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Code to illustrate the 
// Properties of Collection class
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
   
class GFG {
   
    // Driver code
    public static void Main()
    {
          
        // Creating a collection of strings
        Collection<string> myColl = new Collection<string>();
   
        // Adding elements in Collection myColl
        myColl.Add("A");
        myColl.Add("B");
        myColl.Add("C");
        myColl.Add("D");
        myColl.Add("E");
          
        // ------- Count Property ----------
          
        // To print the count of
        // elements in Collection
        Console.WriteLine("Count : " + myColl.Count);
   
        // -------- Item[Int32] Property --------
          
        // Get the element at index 2
        Console.WriteLine("Element at index 2 is : " + myColl[2]);
   
        // Get the element at index 3
        Console.WriteLine("Element at index 3 is : " + myColl[3]);
    }
}

chevron_right


Output:

Count : 5
Element at index 2 is : C
Element at index 3 is : D

Methods

Method Description
Add(T) Adds an object to the end of the Collection<T>.
Clear() Removes all elements from the Collection<T>.
ClearItems() Removes all elements from the Collection<T>.
Contains(T) Determines whether an element is in the Collection<T>.
CopyTo(T[], Int32) Copies the entire Collection<T> to a compatible one-dimensional Array, starting at the specified index of the target array.
Equals(Object) Determines whether the specified object is equal to the current object.
GetEnumerator() Returns an enumerator that iterates through the Collection<T>.
GetHashCode() Serves as the default hash function.
GetType() Gets the Type of the current instance.
IndexOf(T) Searches for the specified object and returns the zero-based index of the first occurrence within the entire Collection<T>.
Insert(Int32, T) Inserts an element into the Collection<T> at the specified index.
InsertItem(Int32, T) Inserts an element into the Collection at the specified index.
MemberwiseClone() Creates a shallow copy of the current Object.
Remove(T) Removes the first occurrence of a specific object from the Collection<T>.
RemoveAt(Int32) Removes the element at the specified index of the Collection<T>.
RemoveItem(Int32) Removes the element at the specified index of the Collection<T>.
SetItem(Int32, T) Replaces the element at the specified index.
ToString() Returns a string that represents the current object.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to check if an
// element is in the Collection
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a collection of strings
        Collection<string> myColl = new Collection<string>();
  
        myColl.Add("A");
        myColl.Add("B");
        myColl.Add("C");
        myColl.Add("D");
        myColl.Add("E");
  
        // Checking if an element is in the Collection
        // The function returns "True" if the
        // item is present in Collection
        // else returns "False"
        Console.WriteLine(myColl.Contains("A"));
    }
}

chevron_right


Output:

True

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to copy the entire Collection
// to a compatible one-dimensional Array,
// starting at the specified index of
// the target array
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a collection of strings
        Collection<string> myColl = new Collection<string>();
  
        myColl.Add("A");
        myColl.Add("B");
        myColl.Add("C");
        myColl.Add("D");
        myColl.Add("E");
  
        // Creating a string array
        string[] myArr = new string[myColl.Count];
  
        // Copying the entire Collection to a
        // compatible one-dimensional Array,
        // starting at the specified index
        // of the target array
        myColl.CopyTo(myArr, 0);
  
        // Displaying the elements in myArr
        foreach(string str in myArr)
        {
            Console.WriteLine(str);
        }
    }
}

chevron_right


Output:

A
B
C
D
E

Reference:



My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.