Question

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;
}
Was it helpful?

Solution 2

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.

OTHER TIPS

Either is fine. There's no particular technical reason to put it outside, so do whatever fits your style best. Returning from within the using statement is akin to returning from within a try block that has a finally attached to it; either way, the finally block (explicit, or implicit in the case of using) is executed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top