Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does reassigning a disposable object variable work?

In C# when reassigning a disposable object variable with a new object, how does it work in the memory? Will the memory space occupied by the old object simply be overwritten by the new object? Or do I still have to call Dispose() to release the resources it uses?

DisposableThing thing;

thing = new DisposableThing();
//....do stuff
//thing.Dispose();
thing = new DisposableThing();
like image 975
Dan7 Avatar asked Sep 28 '11 23:09

Dan7


1 Answers

In this case you have one slot / reference and two instances of an IDisposable object. Both of these instances must be disposed indepedently. The compiler doesn't insert any magic for IDisposable. It will simply change the instance the reference points to

A good pattern would be the following

using (thing = new DisposableThing()) {
  // ... do stuff
}

thing = new DisposableThing();

Ideally the second use of thing should also be done within a using block

like image 101
JaredPar Avatar answered Oct 12 '22 23:10

JaredPar