In .NET, ICollection is an interface that represents a non-generic collection of objects that can be individually accessed by index (like an array) and allows for adding, removing, and checking for the existence of items. It is part of the System.Collections namespace and serves as the base interface for several collection types in .NET, including List<T>, HashSet<T>, and Queue<T>.

Here are some of the main characteristics and members of the ICollection interface:

  1. Count Property: ICollection has a Count property that returns the number of elements in the collection.
  2. IsReadOnly Property: It includes an IsReadOnly property that indicates whether the collection is read-only or not. A read-only collection allows elements to be read but not modified.
  3. Add Method: The Add method allows you to add an item to the collection.
  4. Remove Method: The Remove method allows you to remove a specific item from the collection.
  5. Contains Method: The Contains method checks whether a specific item is present in the collection.
  6. Clear Method: The Clear method removes all items from the collection.
  7. CopyTo Method: The CopyTo method copies the elements of the collection to an array, starting at a particular index.
  8. GetEnumerator Method: It includes an GetEnumerator method that returns an IEnumerator object, which can be used to iterate through the elements of the collection.

Here’s an example of how you might use ICollection:

using System;
using System.Collections;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        ICollection<int> numbers = new List<int>();

        // Adding elements
        numbers.Add(1);
        numbers.Add(2);
        numbers.Add(3);

        // Count
        Console.WriteLine("Count: " + numbers.Count);

        // Contains
        bool containsTwo = numbers.Contains(2);
        Console.WriteLine("Contains 2: " + containsTwo);

        // Remove
        numbers.Remove(2);
        Console.WriteLine("Count after removing 2: " + numbers.Count);

        // Enumerate
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

In this example, ICollection is used to manage a collection of integers. You can see how elements are added, removed, and checked for existence using the methods provided by the interface.

By davs