Custom Collection Implementing IEnumerable?

The IEnumerable { private readonly List _hrefs = new List(); public void Add(Href href) { _hrefs. Add(href); } public void AddRange(IEnumerable hrefs) { _hrefs. AddRange(hrefs); } public IEnumerator GetEnumerator() { return _hrefs.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_hrefs).GetEnumerator(); } }.

The IEnumerable and IEnumerable interfaces are used to generate a read-only sequence or provide a read-only view of the items in a collection. If you want to be able to add items to your collection then, internally, you'll need to use a data structure that allows items to be added -- for example List. You simply can't add items using the IEnumerable or IEnumerable interfaces.

Public class HrefCollection : IEnumerable { private readonly List _hrefs = new List(); public void Add(Href href) { _hrefs. Add(href); } public void AddRange(IEnumerable hrefs) { _hrefs. AddRange(hrefs); } public IEnumerator GetEnumerator() { return _hrefs.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_hrefs).GetEnumerator(); } }.

This works, but it's still pretty silly and it doesn't serve the purpose of learning how yield works. – Eric Mickelsen May 21 '10 at 15:14 @tehMick: True, but the question says "I want to add an add and addrange function to the following class". I know that the question also mentions using yield return, but the answer is that you just can't use yield return to add items to a collection.

– LukeH May 21 '10 at 15:55.

Foreach( Href href in hrefs ) { yield return href; } should be foreach( Href href in this. Hrefs ) { yield return href; } foreach( Href href in hrefs ) { yield return href; }.

This is not working. – Burnzy May 21 '10 at 14:48 @Burnzy: could you be more specific? – Eric Mickelsen May 21 '10 at 14:54 well if I call addrange, the Collection remains null.

– Burnzy May 21 '10 at 14:56 Actually, you should get rid of the private IEnumerable hrefs; . You're declaring one IEnumerable inside another. Instead, you should be referencing this.

– Eric Mickelsen May 21 '10 at 14:56 @Burzy, but using yield will never add to the collection you have, only output a new collection. – Eric Mickelsen May 21 '10 at 14:58.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions