40

What unmanaged resources does it allocates that needs to be disposed? Isn't it just a simple array of managed data? So why disposing?

Raphael
  • 1,847
  • 1
  • 17
  • 29
  • 3
    Because it implements IDisposable :) – csharptest.net Dec 12 '11 at 17:00
  • 1
    @csharptest.net That is not a reason. – Ci3 Oct 28 '17 at 00:09
  • @Ci3 It is! If something implements IDisposable, its API is asking for disposal. If you don't dispose, something bad might happen. Exceptions might exist, but they're exceptions. – Raphael Oct 31 '17 at 00:45
  • @Raphael I understand why you should dispose objects if they implement that class, but the comment is just an implementation detail. It doesn't explain what the un-managed data in that class is. – Ci3 Oct 31 '17 at 00:49
  • @Ci3 Agreed! But since its just a comment, then I guess it's OK (I would not accept it if it was an answer :) ). – Raphael Oct 31 '17 at 00:51
  • @Raphael Agreed :) – Ci3 Oct 31 '17 at 00:51

2 Answers2

58

A mail message has attachments -> attachments are Streams -> Streams are to be disposed.

Here is the decompiled Dispose method of MailMessage:

    protected virtual void Dispose(bool disposing)
    {
        if (disposing && !this.disposed)
        {
            this.disposed = true;
            if (this.views != null)
            {
                this.views.Dispose();
            }
            if (this.attachments != null)
            {
                this.attachments.Dispose();
            }
            if (this.bodyView != null)
            {
                this.bodyView.Dispose();
            }
        }
    }

As a general rule a class should implement IDisposable if any of its contained children implement it.

Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131
  • 2
    So does that means that if a message don't have any attachments it doesn't need to be disposed? – Raphael Dec 12 '11 at 17:12
  • 5
    @Raphael If something implements IDisposable, you should dispose it. Also you can see that it has other things that it disposes too. – Muhammad Hasan Khan Dec 12 '11 at 17:15
  • 4
    Every rule has its [exceptions](http://stackoverflow.com/questions/913228/should-i-dispose-dataset-and-datatable), but this is not one of the exceptions. – sq33G Dec 12 '11 at 19:55
14

A MailMessage can have attachments, an attachment is represented by MIME part which itself holds a Stream. This Stream needs closing as it might hold an unmanaged pointer to the underlying data.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928