Really, how do you make enumerations?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Gustaf

    #1

    Really, how do you make enumerations?

    I had VS (2008) telling me my class isn't enumerable when trying to use a foreach loop. This happens quite often, and every time I Google around for an hour trying to find a solution that applies to my case. It needs to be understandable and easy to implement. It needs to work with List<Tcollectio ns. It should be the best practice in .NET 3.5. Can anyone point me once and for all to the right solution? The best I can find right now is this:

    http://msdn.microsoft.com/en-us/libr...numerable.aspx

    But I don't want to write all that every time I make a collection lass, and I don't like the public class variable in the enumerator class. Didn't enumerations get a lot easier in .NET 2.0?

    Gustaf


  • Jon Skeet [C# MVP]

    #2
    Re: Really, how do you make enumerations?

    On Sep 24, 11:40 am, Gustaf <gust...@algone t.sewrote:

    <snip>
    But I don't want to write all that every time I make a collection lass,
    and I don't like the public class variable in the enumerator class.
    Didn't enumerations get a lot easier in .NET 2.0?
    Implementing IEnumerable and IEnumerator (and the generic equivalents)
    became a lot easier in C# 2 with iterator blocks (method
    implementations using "yield return" and "yield break" statements).

    See the following links for a couple of articles and a free chapter
    from my book (C# in Depth) which covers iterator blocks:


    Find information, resources and relevant links for manning-source.com. This domain may be for sale.


    Jon

    Comment

    • Marc Gravell

      #3
      Re: Really, how do you make enumerations?

      t needs to work with List<Tcollectio ns.
      Can you clarify what you have already? If you have a class that is
      encapsulating a single list, then you can simply forward the list's
      enumerator:

      class Test : IEnumerable<str ing>
      {
      private List<stringinne rList = new List<string>();

      public IEnumerator<str ingGetEnumerato r()
      {
      return innerList.GetEn umerator();
      }
      IEnumerator IEnumerable.Get Enumerator()
      {
      return GetEnumerator() ;
      }
      }

      If you have multiple lists, you can use an iterator block to flatten
      them:

      class Test : IEnumerable<str ing>
      {
      private List<stringlist A = new List<string>(),
      listB = new List<string>();

      public IEnumerator<str ingGetEnumerato r()
      {
      foreach (string s in listA) {yield return s;}
      foreach (string s in listB) { yield return s; }
      }
      IEnumerator IEnumerable.Get Enumerator()
      {
      return GetEnumerator() ;
      }
      }

      If that doesn't help, can you clarify what you have?

      Marc

      Comment

      Working...