Sunday, June 21, 2026

C# Example of Implementing IReadOnlyCollection generic collection

Step1. Create a class that implements IReadOnlyCollection<T>
lass MyReadOnlyCollection<T> : IReadOnlyCollection<T>
{
    private readonly T[] _items; // Added 'readonly' for safety

    public MyReadOnlyCollection(T[] items)
    {
        // Prevent null reference issues
        _items = items ?? throw new ArgumentNullException(nameof(items));
    }

    public int Count => _items.Length;

    public IEnumerator<T> GetEnumerator()
    {
        return new ReadOnlyCollectionEnumerator<T>(_items);

        // Pro-tip: If you didn't want to build a custom enumerator, you could just do:
        // return ((IEnumerable<T>)_items).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator(); // Best practice: call the generic version to avoid duplication
    }
}
Step2. Create a class that implements IEnumerator<T>
class ReadOnlyCollectionEnumerator<T> : IEnumerator<T>
{
    private readonly T[] _items;
    private int _position = -1;

    public ReadOnlyCollectionEnumerator(T[] items)
    {
        _items = items;
    }

    public T Current
    {
        get
        {
            if (_position < 0 || _position >= _items.Length)
            {
                throw new InvalidOperationException(
                    "Enumeration has either not started or has already finished.");
            }
            return _items[_position];
        }
    }

    object IEnumerator.Current => this.Current;

    public void Dispose()
    {
        // Correctly left empty since arrays don't have unmanaged resources
    }

    public bool MoveNext()
    {
        // Increment first, then check if we are within the boundaries
        if (_position < _items.Length - 1)
        {
            _position++;
            return true;
        }
        return false;
    }

    public void Reset()
    {
        _position = -1;
    }
}
Step3. Create a class that consumes MyReadOnlyCollection<T>
lass Program
{
    static void Main(string[] args)
    {
        // Testing the collection
        string[] colorArray = { "Red", "Green", "Blue" };
        MyReadOnlyCollection<string> colors = new MyReadOnlyCollection<string>(colorArray);

        foreach (var color in colors)
        {
            Console.WriteLine(color);
        }
        Console.WriteLine("Total colors: " + colors.Count);
    }
}

No comments:

Post a Comment

Hot Topics