Reputation: 118
Below are 2 methods that are almost identical. I would like to know if there's any difference in how or when the context object will be disposed?
public List<Template> MethodVu()
{
List<Template> templates;
using (var context = new Entities())
{
templates = context.Templates.ToList();
}
return templates;
}
public List<Template> MethodDo()
{
using (var context = new Entities())
{
return context.Templates.ToList();
}
}
Upvotes: 0
Views: 50
Reputation: 16553
No difference. In both cases, context.Dispose()
will be called immediately when leaving the using
block. The fact that you store the result in a variable and then return it or just return it makes no difference (irrelevant to the dispose, but in this specific example I'm guessing the compiler will optimize that away anyway).
What makes you ask the question?
More details: using
is equivalent to a try...finally
in the following sense.
The code:
using (var context = new Entities())
{
return context.Templates.ToList();
}
...is exactly equivalent to:
{
var context = new Entities();
try {
return context.Templates.ToList();
}
finally {
if (context != null) { context.Dispose(); }
}
}
See the docs for more.
Upvotes: 2