IReadOnlyCollection<T> Interface

System.Collections.Generic

Represents a collection that can be counted but cannot be modified.

Inheritance

IReadOnlyCollection<T> inherits from IEnumerable<T>.

public interface IReadOnlyCollection<out T> : IEnumerable<T>

Implementations

IReadOnlyCollection<T> is implemented by the following types:

Members

Name Description
Count Gets the number of elements in the collection.

Remarks

The IReadOnlyCollection<T> interface is the base interface for collections that expose their count.

Collections that implement IReadOnlyCollection<T> are guaranteed to have a Count property that returns the number of elements in the collection. They are also guaranteed to implement IEnumerable<T>, which provides an enumerator for the collection.

This interface is intended for scenarios where a collection needs to be read but not modified. It provides a way to get the size of the collection without allowing for additions or removals.

Examples

The following example demonstrates how to use the IReadOnlyCollection<T> interface to iterate over a collection and get its count.

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main(string[] args)
    {
        List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };

        // Cast to IReadOnlyCollection<T> to access the Count property
        IReadOnlyCollection<string> readOnlyFruits = fruits;

        Console.WriteLine($"Number of fruits: {readOnlyFruits.Count}"); // Output: Number of fruits: 3

        Console.WriteLine("Fruits:");
        foreach (string fruit in readOnlyFruits)
        {
            Console.WriteLine($"- {fruit}");
        }
        // Output:
        // - Apple
        // - Banana
        // - Cherry
    }
}