Reputation: 49
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
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
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
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
Reputation: 125650
You have to import System.Collection
to get rid of namespace could not be found error.
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