1

For example a have a class:

public class MyClass{
   Bitmap bmp;
}

The Bitmap class is disposable.

In case when I do not implement IDisposable in MyClass and there is no no references to instance of MyClass, it means that there is no references to instance of Bitmap class, so the GarbageCollector will call finalizer of Bitmap and all unmanaged resources will be released.

Why code analyzers recommend to Implement IDisposable in MyClass?

Eugene Maksimov
  • 1,504
  • 17
  • 36
  • Yes, it will be collected at some point, just not deterministically. – leppie Aug 26 '14 at 12:12
  • http://habrahabr.ru/post/89720/ (the resource in Russian, alas) – Dmitry Bychenko Aug 26 '14 at 12:13
  • @DmitryBychenko There's a such thing called [Google Translate](http://translate.google.com/) -- Or a free browser with that built in! ([Google Chrome](http://www.google.com/chrome/browser/)) :) – Cullub Aug 26 '14 at 12:23

2 Answers2

4

Maybe it will. But when? This class cannot reliably be used. If I create 10.000 sequentially, 10.000 undisposed Bitmaps will be in memory, waiting for the lazy garbage collector to call the finalizer to (hopefully) call Dispose. Maybe today. Maybe tomorrow. But as a developer, I cannot control this. If you implement IDisposable correctly, I can simply have a using block around each of them and I will never use more resources than a single Bitmap will take.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • 1
    just for clarification: you can't even control this by forcing the GC to collect? –  Aug 26 '14 at 12:18
  • @AndreasNiedermair Maybe you can. But forcing the GC to collect is the direct opposite of garbage collected development. And if the OP does not even implement IDisposable, how would we *know* if we even have to call GC.Collect? You cannot call GC.Collect every other statement just in case the OP didn't program it's 3rd party library correctly. – nvoigt Aug 26 '14 at 12:25
  • that's very clear to me ;) just for clarification (and maybe a hint for the OP) –  Aug 26 '14 at 12:34
1

There are 2 reason to implement IDispose:
1. Disposal of unmanaged resources - this is about WHAT to clean up (the unmanaged resources)
2. To be able to control when managed resources are freed - this is about WHEN things get cleaned up.
The IDisposable documention focuses very heavily on 1. but in in reality most implmentations are about 2.
That is the case in your example - the resources you have are managed (by the managed Bitmap class that wraps the unmanaged bitmap handle). You would dispose it in your dispose to enable users of your class to control when the bitmap was freed (NOT if it gets freed - it will be, eventually, when the GC feels like it).

Ricibob
  • 7,505
  • 5
  • 46
  • 65