Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8046175
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T05:43:29+00:00 2026-06-05T05:43:29+00:00

Imagine you have a method that internally uses an IDisposable object (for example a

  • 0

Imagine you have a method that internally uses an IDisposable object (for example a streamreader), and yield returns items as they are read from the file. Like this:

public IEnumerable<YourObject> Read(string filename)
{
    using(var filestream = new FileStream(filename, FileMode.Open))
    {
        using(var reader = new StreamReader(filestream))
        {
            string line;

            while((line = reader.ReadLine()) != null)
            {
                yield return new YourObject(line);
            }
        }
    }
}

Will the reader and the filestream be disposed when I use LINQ-methods that doesn’t iterate the complete collection?

YourOjbect firstLine = Read("myfile.txt").First();
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T05:43:30+00:00Added an answer on June 5, 2026 at 5:43 am

    When you use yield keyword compiler generates nested class, which implements IEnumerable, IEnumerator and IDisposable and stores all context data:

    [CompilerGenerated]
    private sealed class <Read>d__0 : IEnumerable<YourObject>, IEnumerable, IEnumerator<YourObject>, IEnumerator, IDisposable
    {
        // Fields
        private int <>1__state;
        private YourObject <>2__current;
        public string <>3__filename;
        public Foo <>4__this;
        private int <>l__initialThreadId;
        public FileStream <filestream>5__1;
        public string <line>5__3;
        public StreamReader <reader>5__2;
        public string filename;
    
        // Methods
        [DebuggerHidden]
        public <Read>d__0(int <>1__state);
        private void <>m__Finally4();
        private void <>m__Finally5();
        private bool MoveNext();
        [DebuggerHidden]
        IEnumerator<YourObject> IEnumerable<YourObject>.GetEnumerator();
        [DebuggerHidden]
        IEnumerator IEnumerable.GetEnumerator();
        [DebuggerHidden]
        void IEnumerator.Reset();
        void IDisposable.Dispose();
    
        // Properties
        YourObject IEnumerator<YourObject>.Current { [DebuggerHidden] get; }
        object IEnumerator.Current { [DebuggerHidden] get; }
    }
    

    As you can see, all local variables from context of the yielding method are moved to fields of this generated class. Interesting methods are those which have m_Finally in their names:

    private void <>m__Finally4()
    {
        this.<>1__state = -1;
        if (this.<filestream>5__1 != null)
        {
            this.<filestream>5__1.Dispose();
        }
    }
    

    As you can see, these methods dispose your disposable objects (FileStream and StreamReader). When the called? At the end of enumerating, or when Dispose is called:

    private bool MoveNext()
    {
        bool CS$1$0000;
        try
        {
            int CS$4$0001 = this.<>1__state;
            if (CS$4$0001 != 0)
            {
                if (CS$4$0001 != 3)
                {
                    goto Label_00AB;
                }
                goto Label_0074;
            }
            this.<>1__state = -1;
            this.<filestream>5__1 = new FileStream(this.filename, FileMode.Open);
            this.<>1__state = 1;
            this.<reader>5__2 = new StreamReader(this.<filestream>5__1);
            this.<>1__state = 2;
            while ((this.<line>5__3 = this.<reader>5__2.ReadLine()) != null)
            {
                this.<>2__current = new YourObject(this.<line>5__3);
                this.<>1__state = 3;
                return true;
            Label_0074:
                this.<>1__state = 2;
            }
            this.<>m__Finally5();
            this.<>m__Finally4();
        Label_00AB:
            CS$1$0000 = false;
        }
        fault
        {
            this.System.IDisposable.Dispose();
        }
        return CS$1$0000;
    }
    
    void IDisposable.Dispose()
    {
        switch (this.<>1__state)
        {
            case 1:
            case 2:
            case 3:
                try
                {
                    switch (this.<>1__state)
                    {
                        case 2:
                        case 3:
                            break;
    
                        default:
                            break;
                    }
                    try
                    {
                    }
                    finally
                    {
                        this.<>m__Finally5();
                    }
                }
                finally
                {
                    this.<>m__Finally4();
                }
                break;
        }
    }
    

    If you look to First() implementation of Enumerable, then you’ll see – it calls Dispose after returning first item:

    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
       if (enumerator.MoveNext())
       {
           return enumerator.Current;
       }
    }
    

    Thus Dispose of auto-generated class will be called, and all local variables, which require disposing will be disposed by calls to m_Finally methods.

    BTW (not about usage with LINQ) if you look at foreach statement implementation you’ll see that enumerator is disposed after enumerating. Thus Dispose on generated class will be called even in case of break or exception.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'd like your opinion on the following subject: Imagine we have a method that
I'm defining some types via System.Reflection.Emit. Imagine that I want to have method signature
Imagine i have an extension method that operates of an interface of abstract objects:
Is it normal to modify setter arguments? Let's imagine that we have setString method.
Imagine I have a method: void Method(bool parameter){ if(parameter){ // first case } else
Imagine you have an entity that has some relations with other entities and you
Imagine you have a large dataset that may or may not be filtered by
Imagine I have a game with a base Entity class, with an init method
I have a method here that is supposed to produce a System.Drawing.Image instance. Consider
Is it possible to create an extension method that returns the instance that is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.