For example, in the below code an ‘image’object will be created and then garbage collected at some unknown point in the future
void MyFunction() {
Bitmap image = RetrieveImage();
DoSomething(image);
}
What about
void MyFunction() {
DoSomething(RetrieveImage());
}
In this case is the object garbage collected once it moves out of scope i.e. After the end of MyFunction. If not is there somewhere to enforce this?
No. In fact, you don’t really want it to be garbage collected – prompting the garbage collector very frequently will reduce performance.
What you do want is to dispose of the unmanaged resources in a timely manner – and that’s where
IDisposablecomes in, along with theusingstatement:That will call
image.Dispose()as it leaves theusingstatement, whether or notDoSomethingthrew an exception.You do have to use the extra variable though – unless you change
DoSomethingto take aFunc<Bitmap>instead, so instead of:you’d have:
Note that that doesn’t give the opportunity to pass in a bitmap without it being disposed – which could be a problem if you want to use it again later. Still, it’s a nice technique to at least know about.
EDIT: As mbeckish has pointed out in his comments, there isn’t very much benefit here over just disposing of the bitmap within
RetrieveImage. Here’s a variant on the pattern though:Here the “acquire and dispose” logic is encapsulated, without the caller worrying about it – but the caller can still be very flexible in terms of the complexity of logic they pass in.