DEV Community

Admir Mujkic
Admir Mujkic

Posted on

Unpacking Collections in C#

The objective of this article is to provide practical examples of some of the most commonly used collection types in C#, and to examine their usage more closely. Our focus will be on effectively leveraging .NET collections to optimize the programming workflow.

Image description

Demystifying ICollection and ICollection

When we speak about ICollection we can say is like a interface that helps you work with groups of things, like a box of toys. It can tell you how many toys are in the box, if a specific toy is in the box, and even give you a list of all the toys. If the box is not read-only, meaning you can add or take out toys, you can also use ICollection to add new toys, remove old ones, or clear out the entire box. And, you can use it with the foreach statement.

public interface ICollection<T> : IEnumerable<T>, IEnumerable
{
      int Count { get; }
      bool Contains (T item);
      void CopyTo (T[] array, int arrayIndex);
      bool IsReadOnly { get; }
      void Add(T item);
      bool Remove (T item);
      void Clear();
}
Enter fullscreen mode Exit fullscreen mode

In another hand the non generic ICollection is like a countable collection, but you can’t add or remove items from it, and you can’t check if a certain item is in the collection. It’s mostly just for counting the number of items in a collection.

public interface ICollection : IEnumerable
{
      int Count { get; }
      bool IsSynchronized { get; }
      object SyncRoot { get; }
      void CopyTo (Array array, int index);
}
Enter fullscreen mode Exit fullscreen mode

IList vs IList: Exploring the Differences and Similarities in C# Collections

One of the most popular interface is IList. This is another interface for collections, but...

Read more

Top comments (0)