CodeKicks.com
Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Monday, April 06, 2009

Using custom collection. Looping using IEnumerator and IEnumerable in CollectionBase

 

Suppose we have a entity Test and have a list of Tests as TestList entity.

Inorder to  loop through the TestList. Implement the TestList class from Collectionbase We have to create a TestEnumerator class that implements the IEnumerator and implement the method GetEnumerator() in IEnumerable and return TestEnumerator as outlined.

#region Nested type: TestEnumerator

    /// <summary>
    /// TestEnumerator
    /// </summary>
    internal class TestEnumerator : IEnumerator//, IDisposable
    {
        private TestList collection;
        private int nIndex;

        /// <summary>
        /// TestEnumerator

        /// </summary>
        /// <param name="coll">TestList </param>
        public TestEnumerator (TestList coll)
        {
            collection = coll;
            nIndex = -1;
        }

        /// <summary>
        /// Current
        /// </summary>
        /// <value>object</value>
        public object Current
        {
            get { return collection.List[nIndex]; }
        }

        //#region IDisposable Members

        ///// <summary>
        ///// Dispose
        ///// </summary>
        //public void Dispose()
        //{
        //    collection = null;
        //}

        //#endregion

        #region IEnumerator Members

        /// <summary>
        /// Reset
        /// </summary>
        public void Reset()
        {
            nIndex = -1;
        }

        /// <summary>
        /// MoveNext
        /// </summary>
        /// <returns>bool</returns>
        public bool MoveNext()
        {
            nIndex++;
            return (nIndex < collection.List.Count);
        }

        /// <summary>
        /// this property returns the current object
        /// </summary>
        object IEnumerator.Current
        {
            get { return (Current); }
        }

        #endregion
    }

    #endregion

#region IEnumerable Members

/// <summary>
/// GetEnumerator
/// </summary>
/// <returns>TestEnumerator</returns>
public new IEnumerator GetEnumerator()
{
    return new TestEnumerator(this);
}

#endregion

Post a Comment