HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpModerate

Implement `Dispose` method in C#

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
disposeimplementmethod

Problem

I have a class:

public class EmailSender: IDisposable
{
    private SmtpClient EmailSmtpClient { get; set; }
    private MailMessage Message { get; set; } 

    public override void Dispose()
    {
         EmailSmtpClient.Dispose();
         Message.Dispose();
         GC.Collect();
    } 
}


This is what I currently have implemented. What is the best way to release all the resources including the attachments (that are a part of MailMessage) immediately after the email is sent? Can anyone review my Dispose method and suggest some betterment? I will be thankful :)

Solution

I would suggest that you read these pieces from MSDN:

Basic Dispose Pattern,
Implementing a Dispose Method

Some things that immediately stand out from your example:

  • Replace your GC.Collect() with GC.SuppressFinalize(this)



  • Check your resources aren't null before attempting to dispose them.



  • Check that your objects haven't already been disposed.



All of this is easily done by following the dispose pattern.

Context

StackExchange Code Review Q#162514, answer score: 11

Revisions (0)

No revisions yet.