yield and Dispose()

This is a discussion on yield and Dispose() within the C# Programming forums, part of the General Programming Boards category; Consider this code: Code: class Test : IDisposable { public void Dispose() { Console.WriteLine("dispose"); } } static IEnumerable<int> Bla() { ...

  1. #1
    Registered User
    Join Date
    Jan 2007
    Posts
    330

    yield and Dispose()

    Consider this code:

    Code:
        class Test : IDisposable
        {
            public void Dispose()
            {
                Console.WriteLine("dispose");
            }
        }
    
        static IEnumerable<int> Bla()
            {
                using (new Test())
                {
                }
                yield return 1;
                yield return 2;
                yield return 3;
            }
    I would expect after the using statement that dispose of Test is called when calling Bla(). But it isn't
    Dispose is only called when calling Bla in a loop.

    Code:
    foreach (int i in Bla()) {break;}
    Why?

  2. #2
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,139
    That's because before you actually materialize your enumerable, Blah() isn't even called. Put a writeline before the new and you will see.

    Code:
    IEnumerable<int> GetAllData() 
    {
    yield 1;
    yield 2;
    yield 3;
    }
    
    var data = GetAllData(); // <- function is NOT called. You got an IEnumerable. Not the actual data, but rather a hint where to get data, should it really be enumerated.
    
    var materialized_data = data.ToList(); // <- now it gets called, the list will materialize the data
    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

  3. #3
    Registered User
    Join Date
    Jan 2007
    Posts
    330
    I see, thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to dispose of unused characters
    By C++Newb in forum C++ Programming
    Replies: 8
    Last Post: 10-19-2009, 09:38 PM
  2. yield return
    By George2 in forum C# Programming
    Replies: 6
    Last Post: 05-07-2008, 07:16 AM
  3. Dispose pattern in class derivation
    By George2 in forum C# Programming
    Replies: 5
    Last Post: 04-19-2008, 05:03 AM
  4. dispose wrapped resource
    By George2 in forum C# Programming
    Replies: 0
    Last Post: 04-15-2008, 08:45 AM
  5. Replies: 17
    Last Post: 07-20-2007, 09:25 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21