so lately i've been working with disposable object and i was wondering would it be benific to dispose an object inside a function ? like between those 2 functions is the use of .Dispose() really matters inside a function since all objects within a function will vanish as soon as it finishes
void FOO()
{
var x= new DisposableObject();
//stuff
}
void FOO()
{
using(var x= new DisposableObject())
{
//stuff
}
}
All objects within a function will vanish as soon as it finishes
The objects will stay, the local references will vanish. The objects will 'vanish' when garbage collector runs and determines they are unreachable.
Before an unreachable object is removed from memory, it's finalizer will run (if implemented), cleaning all unmanaged resources.
The problem is that all that is not deterministic. You never know when GC will run, in some cases the finalizer will not even be executed.
You should always call Dispose
method if it's possible.
If you want more details about finalizers, you should read these 2 articles: part 1, part 2.