Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing IList interface

I am new to generics. I want to implement my own collection by deriving it from IList<T> interface.

Can you please provide me some link to a class that implements IList<T> interface or provide me a code that at least implements Add and Remove methods?

like image 331
Ashish Ashu Avatar asked Jul 24 '09 08:07

Ashish Ashu


1 Answers

In addition to deriving from List<T>, you can facade List<T> and add more features to your facade class.

class MyCollection<T> : IList<T>
{
    private readonly IList<T> _list = new List<T>();

    #region Implementation of IEnumerable

    public IEnumerator<T> GetEnumerator()
    {
        return _list.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    #endregion

    #region Implementation of ICollection<T>

    public void Add(T item)
    {
        _list.Add(item);
    }

    public void Clear()
    {
        _list.Clear();
    }

    public bool Contains(T item)
    {
        return _list.Contains(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        _list.CopyTo(array, arrayIndex);
    }

    public bool Remove(T item)
    {
        return _list.Remove(item);
    }

    public int Count
    {
        get { return _list.Count; }
    }

    public bool IsReadOnly
    {
        get { return _list.IsReadOnly; }
    }

    #endregion

    #region Implementation of IList<T>

    public int IndexOf(T item)
    {
        return _list.IndexOf(item);
    }

    public void Insert(int index, T item)
    {
        _list.Insert(index, item);
    }

    public void RemoveAt(int index)
    {
        _list.RemoveAt(index);
    }

    public T this[int index]
    {
        get { return _list[index]; }
        set { _list[index] = value; }
    }

    #endregion

    #region Your Added Stuff

    // Add new features to your collection.

    #endregion
}
like image 127
tranmq Avatar answered Oct 04 '22 04:10

tranmq