1
public class CaptchaImage {
    public Bitmap Image {
        get { return this.image; }
    }

    private Bitmap image;

    ~CaptchaImage() {
        Dispose(false);
    }

    public void Dispose() {
        GC.SuppressFinalize(this);
        this.Dispose(true);
    }

    protected virtual void Dispose(bool disposing) {
        if (disposing)
            // Dispose of the bitmap.
            this.image.Dispose();
        }
    }

Is this the correct way of disposing of a Bitmap image? We are using the destructor to free the allocated memory. Is it correct or do we have any better alternatives?

dda
  • 6,030
  • 2
  • 25
  • 34
Sahil Sharma
  • 3,847
  • 6
  • 48
  • 98
  • 1
    You need to explicitly implement the disposable interface _"public class CaptchaImage : IDisposable"_ – PaulF Oct 03 '17 at 07:52
  • could you share example code? – Sahil Sharma Oct 03 '17 at 07:56
  • 2
    @maverick He did. You basically have everything except the actual `IDisposable` interface declaration on the class. – ProgrammingLlama Oct 03 '17 at 07:58
  • Add the interface, make the class `sealed` and then you can remove the ~destructor. – H H Oct 03 '17 at 08:02
  • Can anyone explain why "protected virtual void Dispose" this method should be virtual, any point of having it as virtual method in this case? – Sahil Sharma Oct 03 '17 at 08:04
  • Unless the class is sealed as per @HenkHolterman - you or someone else may derive a further class from it which also needs to dispose of other resources - if referenced via your base class then the correct dispose method will not be called. The protected dispose method is not intended to be called explicitly via the code - just the public Dispose method. – PaulF Oct 03 '17 at 08:17
  • And if this becomes sealed class, there's no point of having virtual method, so I can remove that too – Sahil Sharma Oct 03 '17 at 08:35
  • https://stackoverflow.com/questions/18336856/implementing-idisposable-correctly here they have recommended virtual implementation, i think that is to implement dispose in any child classes – Sahil Sharma Oct 03 '17 at 08:49
  • The whole Disposable pattern is much complicated by the possibility of a derived class needing to Dispose() as well. And we usually don't need/want to be a base class. When you seal the class you can be sure you don't need the virtual or the ~destructor. – H H Oct 03 '17 at 09:03
  • This is just to be sure that no one can derive from this class.. if that is not the worry, we can just put IDisposable and it would be fine – Sahil Sharma Oct 03 '17 at 09:16

0 Answers0