Tag Archives: using

C#

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