Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return inside out 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;
}
like image 915
Fred Avatar asked Feb 03 '14 13:02

Fred


2 Answers

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.

like image 128
T.J. Crowder Avatar answered Sep 20 '22 18:09

T.J. Crowder


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.

like image 25
Sergey Kalinichenko Avatar answered Sep 22 '22 18:09

Sergey Kalinichenko