Return statement in using block in C#

using
You may use such very lazy C# statement as using (proof)
But beginner programmers often repeat mistake like this: for example you want to download data from the internet using stream but return web-headers:

public static WebHeaderCollection Download(string url, string filePath)
{
    using (var client = new WebClient())
    {
        using (var stream = client.OpenRead(url))
        {
            using (var file = File.Create(filePath))
            {
                stream.CopyTo(file);
                return client.ResponseHeaders;
            }
        }
    }
}

Be aware of such case. The right (recommended) way is as this:

public static WebHeaderCollection Download(string url, string filePath)
{
    WebHeaderCollection result = null;
    using (var client = new WebClient())
    {
        using (var stream = client.OpenRead(url))
        {
            using (var file = File.Create(filePath))
            {
                stream.CopyTo(file);
            }
        }
        result = client.ResponseHeaders;
    }
    return result;
}

As you see, return statement is moved down after the using statement closing.

See also, http://stackoverflow.com/questions/662773/returning-in-the-middle-of-a-using-block

  • jon

    Hi, Can you help me understand what is wrong with the “Wrong Way” example and right with the “Right Way” example?

    I ran both examples in LinqPad and both appear to work. The URL was copied to the file I specified and the ResponseHeaders were returned. I also verified that the client, stream, and file were all called dispose.

    Thanks

  • Bennow

    Hi. Yea, you right it works… but if you try to make 100 requests sequentially, you’ve got “Timeout error” because of resource locked. In my case that happens exactly. So, it is better to return outside of using block.