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:
- Count Property:
ICollectionhas aCountproperty that returns the number of elements in the collection. - IsReadOnly Property: It includes an
IsReadOnlyproperty that indicates whether the collection is read-only or not. A read-only collection allows elements to be read but not modified. - Add Method: The
Addmethod allows you to add an item to the collection. - Remove Method: The
Removemethod allows you to remove a specific item from the collection. - Contains Method: The
Containsmethod checks whether a specific item is present in the collection. - Clear Method: The
Clearmethod removes all items from the collection. - CopyTo Method: The
CopyTomethod copies the elements of the collection to an array, starting at a particular index. - GetEnumerator Method: It includes an
GetEnumeratormethod that returns anIEnumeratorobject, 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.
