Using foreach in class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sridhard2406
    New Member
    • Dec 2007
    • 52

    Using foreach in class

    Hi All ,
    I am new into C#, i want to use my class into foreach, I am using IEnumerable and IEnumerator interface in my class implementation, When I compile my code i got below mentioned error.


    Error 'ConsoleApplica tion2.entries.M yenum' does not implement interface member 'System.Collect ions.IEnumerato r.Current' C:\Users\t_srid hardh1\Document s\Visual Studio 2008\Projects\C onsoleApplicati on2\ConsoleAppl ication2\Progra m.cs 32 22 ConsoleApplicat ion2



    Code:
    
    using System;
    using System.Collections;
    using System.Linq;
    using System.Text;
    
    
    namespace ConsoleApplication2
    {
        class Program
        {
            static void Main(string[] args)
            {
                entries list = new entries();
    
                foreach (int l in list)
                {
                    Console.WriteLine(l);
                }
    
            }
        }
    
        class entries : IEnumerable
        {
            static int[] list = { 2, 3, 4, 5, 6 };
    
            public IEnumerator GetEnumerator()
            {
                return new Myenum() ;
            }
    
           private class Myenum : IEnumerator
            {
                int index = -1;
                public object current
                {
                    get { return list[index]; }
                }
                public bool MoveNext()
                {
                    if (++index >= list.Length)
                        return false;
                    else
                        return true;
                }
                public void Reset()
                {
                    index = -1;
                }
            }
        }
    }
    Please help anybody to resolve this.

    Thanks
    Last edited by Curtis Rutland; Jan 7 '11, 11:02 PM.
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    The problem is exactly as the error states... the MyEnum class inherits from IEnumerable but doesn't implement the methods from that interface. You have to implement the interface wherever you inherit from it.

    Comment

    • Curtis Rutland
      Recognized Expert Specialist
      • Apr 2008
      • 3264

      #3
      There's an example on this page:

      Exposes an enumerator, which supports a simple iteration over a non-generic collection.


      That shows how to implement IEnumerable properly.

      Comment

      Working...