IEnumerable vs IEnumerable<T>

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • nick_tucker@hotmail.com

    IEnumerable vs IEnumerable<T>

    Hi,

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

    public class MyCollection:Sy stem.Collection s.IEnumerable
    {
    private List<MyItem> m_MyItemsList

    System.Collecti ons.IEnumerator
    System.Collecti ons.IEnumerable .GetEnumerator( )
    {
    return m_MyItemsList.G etEnumerator();
    }
    }

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


    public class MyCollection:IE numerable<MyIte m>
    {
    private List<MyItem> m_MyItemsList

    System.Collecti ons.IEnumerator
    System.Collecti ons.IEnumerable .GetEnumerator( )
    {
    return m_MyItemsList.G etEnumerator();
    }

    public IEnumerator<MyI tem> 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

  • Marc Gravell

    #2
    Re: IEnumerable vs IEnumerable&lt; T&gt;

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

    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.G etEnumerator(); " should be
    sufficient? does this fail?

    Marc


    Comment

    Working...