Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return inside using statement

I've got the following function, which takes an employee id and returns if the employee is active.

public employee GetEmployee(int empId)
{ 
  using(var dbcontext = new dbentities())
  {
    return dbcontext.employee.Where(emp => emp.id == empId and emp.IsActive == true);
  }
}

Question: I used a using statement so whenever the using block ends the object created inside the using statement will get disposed. Here, though, I've written return statement before the actual using block ends, so will my object will be disposed or not? Is my approach correct? How does the dispose happen?

like image 403
Prakash Avatar asked Nov 18 '13 14:11

Prakash


1 Answers

The only thing that gets disposed is the thing explicitly stated in the using block - i.e. the thing assigned to dbcontext. The actual employee object is not disposed, and is fully usable - but, any features like lazy loading or object navigation will refuse to work since the data-context is unavailable.

Btw - it should probably be Single or SingleOrDefault:

return dbcontext.employee.Single(
   emp => emp.id == empId and emp.IsActive == true);

Technically, at the IL level you can't ret inside a try block (this applies to all code, not just using), so it is actually implemented as if it were written:

public employee GetEmployee(int empId)
{
    employee <>tmp;
    dbentities dbcontext = new dbentities();
    try {
      <>tmp = dbcontext.employee.Single(
         emp => emp.id == empId and emp.IsActive == true);
    } finally {
      if(dbcontext != null) ((IDisposable)dbcontext).Dispose();
      // note that for classes this cast is a no-op and doesn't need any IL;
      // the above gets a little more complex for structs - using
      // constrained call and no null-check
    }
    return <>tmp;
}
like image 62
Marc Gravell Avatar answered Oct 24 '22 05:10

Marc Gravell