Should I do the return
inside or outside the using
statement?
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;
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With