Search code examples
c#returnusing-statement

Return inside or outside the using statement?


Should I do the return inside or outside the usingstatement?

public IEnumerable<Foo> GetData()
{
    using (var db = new DbContext())
    {
        return db.Foo().ToList();
    }
}

or

public IEnumerable<Foo> GetData()
{
    IEnumerable<Foo> foo;

    using (var db = new DbContext())
    {
        foo = db.Foo().ToList();
    }

    return foo;
}

Solution

  • It does not matter. Effectively, the same thing is going to happen - namely, the data that you are about to return will be saved in a temporary for the duration of calling the Dispose() method on the db object.

    Different shops prefer different coding standards. For example, some shops insist on not having returns except on the last line; in this case, the second alternative needs to be used. I prefer the first snippet, because it conveys the same meaning with fewer variables, and less code overall.