ICollection<T> Interface
Namespace: System.Collections.Generic
Overview
The ICollection<T>
interface defines size, enumeration, and synchronization methods for all generic collections.
Syntax
public interface ICollection<T> : IEnumerable<T>, IEnumerable
{
int Count { get; }
bool IsReadOnly { get; }
void Add(T item);
void Clear();
bool Contains(T item);
void CopyTo(T[] array, int arrayIndex);
bool Remove(T item);
}
Remarks
All generic collection classes in the System.Collections.Generic
namespace implement ICollection<T>
. It inherits from IEnumerable<T>
, enabling foreach
iteration.
The IsReadOnly
property indicates whether the collection can be modified after creation.
Properties
Name | Type | Description |
---|---|---|
Count | int | The number of elements contained in the collection. |
IsReadOnly | bool | True if the collection is read‑only; otherwise, false. |
Methods
Signature | Description |
---|---|
void Add(T item) | Adds an item to the collection. |
void Clear() | Removes all items from the collection. |
bool Contains(T item) | Determines whether the collection contains a specific value. |
void CopyTo(T[] array, int arrayIndex) | Copies the elements of the collection to an array, starting at a particular index. |
bool Remove(T item) | Removes the first occurrence of a specific object from the collection. |
Examples
The following example demonstrates common ICollection<T>
operations using a List<int>
which implements the interface.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create a list that implements ICollection
ICollection numbers = new List { 1, 2, 3, 4, 5 };
Console.WriteLine("Count: " + numbers.Count);
// Add a new element
numbers.Add(6);
Console.WriteLine("After Add(6): " + string.Join(", ", numbers));
// Check if it contains a value
Console.WriteLine("Contains 3? " + numbers.Contains(3));
// Remove an element
numbers.Remove(2);
Console.WriteLine("After Remove(2): " + string.Join(", ", numbers));
// Copy to array
int[] array = new int[numbers.Count];
numbers.CopyTo(array, 0);
Console.WriteLine("Array copy: " + string.Join(", ", array));
}
}