Reputation: 81342
I have a collection class which contains 1 property - an array of a sub class.
For the sake of the question. I have a basket class, then fruits[] as the one property of basket. The fruit class contains 3 properties for example. Name, Color and Size.
How can I make the basket class behave so that I can use foreach loops on it?
Upvotes: 1
Views: 673
Reputation: 189535
Whilst it may be more desirable to derive from List<Fruit>
here is something to get you started if for some reason that does not suit your requirements:-
public class Basket : IEnumerable<Fruit>
{
private Fruit[] myFruit;
public int Count { get; private set; }
public IEnumerator<Fruit> GetEnumerator()
{
for (int i = 0; i < Count; i++)
yield return myFruit[i];
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Upvotes: 3
Reputation: 129832
From what you've got already, you're able to do this:
foreach(fruit f in myBasket.fruits) { ... }
is that not good enough? if you want to use foreach(fruit f in myBasket)
, you could implement IEnumerable
, and in your getEnumerator
method just bubble the call to fruits.getEnumerator
, but really, I think in that case I would rather have basket inherit a list of fruit:
public class Basket : List<Fruit>() { ... }
and then you would not use the private member fruits
at all.
Upvotes: 4
Reputation: 60276
In this simple case, you can delegate the enumeration to the array, like this:
public class Basket: IEnumerable {
private Fruit[] fruits;
public IEnumerator getEnumerator() {
return fruits.GetEnumerator();
}
}
Upvotes: 3
Reputation: 63310
have a look at this: http://support.microsoft.com/kb/322022
Upvotes: 1