Saturday, June 20, 2026

C# Example of class that Implements ICollection interface

STEP1. Implement ICollection using MyCollection class

MyCollection has collection type field which is initialized inside constructor of MyCollection class. It contains Count property which returns the numbers of total items in the collection _items. The CopyTo method is implemented to return a copy of the array collection from any index as starting point. For simplicity of implementation, thread safety is false.

Note that MyCollection needs MyEnumerator class which implements IEnumerator. In the Setp2. we create MyEnumerator class that implements IEnumerator.
class MyCollection : ICollection
{
    private object[] _items;

    public MyCollection(object[] items)
    {
        _items = items;
    }

    public int Count => _items.Length;

    // Standard non-thread-safe collection implementations return false/this
    public bool IsSynchronized => false;
    public object SyncRoot => this;

    public void CopyTo(Array array, int index)
    {
        // Check for null array
        if (array == null)
            throw new ArgumentNullException(nameof(array));

        // Check for negative index
        if (index < 0)
            throw new ArgumentOutOfRangeException(nameof(index), "Index cannot be negative.");

        // Check if destination array has enough space
        if (array.Length - index < _items.Length)
            throw new ArgumentException("The destination array is not large enough.");

        // Correct way to copy the elements using Array.Copy
        Array.Copy(_items, 0, array, index, _items.Length);
    }

    public IEnumerator GetEnumerator()
    {
        return new MyEnumerator(_items);
    }
}
STEP2. Create MyEnumerator class which Implements IEnumerator

MyEnumerator class implements IEnumerator. The implementation provides the logic of enumeration of collection items using Current property, MoveNext and Reset methods. The Current returns the current item from collection. MoveNext moves to next item in collection and Reset resets the iteration to the beginning item.
using System.Collections;

class MyEnumerator : IEnumerator
{
    private object[] _items;
    private int _index = -1;

    public MyEnumerator(object[] items)
    {
        _items = items;
    }

    public object Current
    {
        get
        {
            // Standard IEnumerator behavior: throw InvalidOperationException 
            // if the enumerator is positioned before the first element or after the last element.
            if (_index < 0 || _index >= _items.Length)
            {
                throw new InvalidOperationException("Enumeration has either not started or has already finished.");
            }
            return _items[_index];
        }
    }

    public bool MoveNext()
    {
        _index++;
        return _index < _items.Length;
    }

    public void Reset()
    {
        _index = -1;
    }
}
STEP3. Consume MyCollection in Program class
public class Program
{
    static void Main(string[] args)
    {
        object[] colors = { "Red", "Blue", "Green", "Pink" };
        MyCollection myCollection = new MyCollection(colors);

        // 1. Print items using the enumerator
        var myCollectionEnumerator = myCollection.GetEnumerator();
        while (myCollectionEnumerator.MoveNext())
        {
            Console.WriteLine(myCollectionEnumerator.Current);
        }
        Console.WriteLine("Total Items in myCollection: " + myCollection.Count);
        Console.WriteLine("---------------------------------------------");

        // 2. Initialize the destination array.
        // Since we are starting at index 1, the array size must be: 1 (offset) + 4 (items) = 5
        object[] newCollection = new object[5];

        // 3. Copy the data
        myCollection.CopyTo(newCollection, 1);

        // 4. Verify the copy worked by printing the new array
        Console.WriteLine("New Array Length: " + newCollection.Length);
        Console.WriteLine("Contents of newCollection:");
        for (int i = 0; i < newCollection.Length; i++)
        {
            // Index 0 will be null because we started copying at index 1
            Console.WriteLine($"Index {i}: {newCollection[i] ?? "null"}");
        }
    }
}

OUTPUT

Red
Blue
Green
Pink
Total Items in myCollection: 4
---------------------------------------------
New Array Length: 5
Contents of newCollection:
Index 0: null
Index 1: Red
Index 2: Blue
Index 3: Green
Index 4: Pink

No comments:

Post a Comment

Hot Topics