IEnumerable vs IEnumerable<T>

N

nick_tucker

Hi,

Could someone tell me which of the following is correct if I want to
make the MyCollection class below enumerable

public class MyCollection:System.Collections.IEnumerable
{
private List<MyItem> m_MyItemsList

System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return m_MyItemsList.GetEnumerator();
}
}

is this fine or should I use the generic IEnumerable interface i.e.


public class MyCollection:IEnumerable<MyItem>
{
private List<MyItem> m_MyItemsList

System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return m_MyItemsList.GetEnumerator();
}

public IEnumerator<MyItem> GetEnumerator()
{
foreach (MyItem oItem in m_MyItemsList)
yield return oItem;
}
}

Are the two classes do the same thing when I the use foreach on
MyCollection class??

Thanks,
Nick
 
M

Marc Gravell

Well, using the generic enumerator can prevent runtime errors of the type
"foreach(WrongClass x in something)", as they are caught at compile-time
instead; so I would stick with IEnumerable<MyItem>.

As for the second block of code - any reason why you have used the yield
return construct? since this is just enumerating the list, and List<T> :
IEnumerable<T>, then "return m_MyItemsList.GetEnumerator();" should be
sufficient? does this fail?

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top