Michelle Farley
Michelle Farley

Reputation: 49

IEnumerable Interface Causing An Error with List

I am supposed to adjust my InvItems class to use the IEnumerable interface, but not use the IEnumerable<> interface. However, when I adjust the class, my List<InvItem> pops up with errors, and I don't understand why.

The error is :

"the type or namespace could not be found."

I think I have to convert the List, but I'm not quite sure how (I've only found instructions for using the IEnumerable <> interface.) Thank you for any help!

public class InvItemList : IEnumerable
{
    private List<InvItem> invItems;

    public InvItemList()
    {
        invItems = new List<InvItem>();
    }

    public IEnumerator GetEnumerator()
    {
        foreach (InvItem in invItems)
        {
            yield return frmNewItem;
        }
    }

Upvotes: 0

Views: 346

Answers (4)

Michelle Farley
Michelle Farley

Reputation: 49

If I use both System.Collections and System.Collections.Generic, and then when declare the class with

public class InvItemList : System.Collections.IEnumerable

the errors resolve.

Upvotes: 0

Rebornix
Rebornix

Reputation: 5270

The namespace for IEnumerable is System.Collections while the one for IEnumerable<T> is System.Collections.Generic.

Make sure you are referencing the correct one.

Upvotes: 1

Alex
Alex

Reputation: 13244

You will need to correct a few errors:

Add:

using System.Collections;

Correct the "foreach" statement:

foreach (InvItem frmNewItem in invItems)

So together it looks like this:

using System.Collections;

public class InvItem
{
}

public class InvItemList : IEnumerable
{
    private List<InvItem> invItems;

    public InvItemList()
    {
        invItems = new List<InvItem>();
    }

    public IEnumerator GetEnumerator()
    {
        foreach (InvItem frmNewItem in invItems)
        {
            yield return frmNewItem;
        }
    }
}

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

  1. You have to import System.Collection to get rid of namespace could not be found error.

  2. You should probably consider using generic IEnumerable<T> interface instead of non-generic IEnumerable.

Here your code fix to make it compile:

public class InvItemList : IEnumerable
{
    private List<InvItem> invItems;

    public InvItemList()
    {
        invItems = new List<InvItem>();
    }

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

I used List<T>.GetEnumerator() method instead od foreach loop, because it looks cleaner.

To implement generic IEnumerable<T> change class declaration and add one additional method:

public class InvItemList : IEnumerable<InvItem>, IEnumerable
{

    // (...)

    IEnumerator<InvItem> IEnumerable<InvItem>.GetEnumerator()
    {
        return invItems.GetEnumerator();
    }
}

Upvotes: 0

Related Questions