Search code examples
c#using-statement

Are there situations where using will not dispose of an object?


Are there any situations where using will not dispose of the object it is supposed to dispose of?

For example,

using(dbContext db = new dbContext()){ ... }

is there any way that after the last } db is still around?

What if there is this situation:

object o =  new object();
using(dbContext db = new dbContext()){
 o = db.objects.find(1);
}

Is it possible that o can keep db alive?


Solution

  • I think you're confusing two concepts: disposing and garbage collection.

    Disposing an object releases the resources used by this object, but it doesn't mean that the object has been garbage collected. Garbage collection will only happen where this are no more references to your object.

    So in your example, db.Dispose will be called at the end of the using block (which will close the connection), but the DbContext will still be referenced by o. Since o is a local variable, the DbContext will be eligible for garbage collection when the method returns.