<p>Here is a sample code to retrieve data from a database using the yield keyword that I found in a few place while googling around :</p>

<pre><code>public IEnumerable&lt;object&gt; ExecuteSelect(string commandText)
{
    using (IDbConnection connection = CreateConnection())
    {
        using (IDbCommand cmd = CreateCommand(commandText, connection))
        {
             connection.Open();
             using (IDbDataReader reader = cmd.ExecuteReader())
             {
                while(reader.Read())
                {
                    yield return reader["SomeField"];
                }
             }
             connection.Close();
        }
    }
}
</code></pre>

<p>Am I correct in thinking that in this sample code, the connection would not be closed if we do not iterate over the whole datareader ? </p>

<p>Here is an example that would not close the connection, if I understand yield correctly..</p>

<pre><code>foreach(object obj in ExecuteSelect(commandText))
{
  break;
}
</code></pre>

<p>For a db connection that might not be catastrophic, I suppose the GC would clean it up eventually, but what if instead of a connection it was a more critical resource?</p>

[{'answer_id': 47529, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 2, 'selected': False, 'text': '<p>Connection will be closed automatically since you\'re using it inside "using" block.</p>\n'}, {'answer_id': 47699, 'author': 'David Schmitt', 'author_id': 4918, 'author_profile': 'https://Stackoverflow.com/users/4918', 'pm_score': 0, 'selected': False, 'text': '<p>Judging from <a href="http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx" rel="nofollow noreferrer">this technical explanation</a>, your code will not work as expected, but abort on the second item, because the connection was already closed when returning the first item.</p>\n\n<p>@Joel Gauvreau : Yes, I should have read on. <a href="http://blogs.msdn.com/oldnewthing/archive/2008/08/14/8862242.aspx" rel="nofollow noreferrer">Part 3</a> of this series explains that the compiler adds special handling for finally blocks to trigger only at the <em>real</em> end.</p>\n'}, {'answer_id': 47746, 'author': 'Joel Gauvreau', 'author_id': 4789, 'author_profile': 'https://Stackoverflow.com/users/4789', 'pm_score': 2, 'selected': False, 'text': '<p>From the simple test I have tried, aku is right, dispose is called as soon as the foreach block exit.  </p>\n\n<p>@David : However call stack is kept between call, so the connection would not be closed because on the next call we would return to the next instruction after the yield, which is the while block.</p>\n\n<p>My understanding is that when the iterator is disposed, the connection would also be disposed with it. I also think that the Connection.Close would not be needed because it would be taken care of when the object is disposed because of the using clause.</p>\n\n<p>Here is a simple program I tried to test the behavior...</p>\n\n<pre><code>class Program\n{\n    static void Main(string[] args)\n    {\n        foreach (int v in getValues())\n        {\n            Console.WriteLine(v);\n        }\n        Console.ReadKey();\n\n        foreach (int v in getValues())\n        {\n            Console.WriteLine(v);\n            break;\n        }\n        Console.ReadKey();\n    }\n\n    public static IEnumerable&lt;int&gt; getValues()\n    {\n        using (TestDisposable t = new TestDisposable())\n        {\n            for(int i = 0; i&lt;10; i++)\n                yield return t.GetValue();\n        }\n    }\n}\n\npublic class TestDisposable : IDisposable\n{\n    private int value;\n\n    public void Dispose()\n    {\n        Console.WriteLine("Disposed");\n    }\n\n    public int GetValue()\n    {\n        value += 1;\n        return value;\n    }\n}\n</code></pre>\n'}, {'answer_id': 47799, 'author': 'Douglas Leeder', 'author_id': 3978, 'author_profile': 'https://Stackoverflow.com/users/3978', 'pm_score': 5, 'selected': True, 'text': "<p>The Iterator that the compiler synthesises implements <code>IDisposable</code>, which <code>foreach</code> calls when the <code>foreach</code> loop is exited.</p>\n\n<p>The Iterator's <code>Dispose()</code> method will clean up the <code>using</code> statements on early exit.</p>\n\n<p>As long as you use the iterator in a <code>foreach</code> loop, <code>using()</code> block, or call the <code>Dispose()</code> method in some other way, the cleanup of the Iterator will happen.</p>\n"}]
['https://Stackoverflow.com/questions/47521', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4789/']