Search code examples
c#.netinheritancedispose

How to Implement Dispose In Inheriting Class


I am using SmtpClient in the .NET-3.5 framework (meaning it does not implement IDisposable), but would like to put it in a using statement like so:

using (var client = new DisposableSmtpClient("mail.domain.com", 25)
{ Credentials = new NetworkCredential(), EnableSsl = false })
{
    client.Send(EmailAddress,
                EmailAddress,
                Subject,
                body);
}

So I created the following:

class DisposableSmtpClient : SmtpClient, IDisposable
{
    bool disposed; 

    public DisposableSmtpClient(string mailServer, int port) : base(mailServer, port)
    {
        // var client = new SmtpClient(mailServer, port);
    }

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

Which works fine for sending the message, but when debugging, it throws a StackOverflow exception (as this.Dispsoe(); will just call itself forever).

I tried calling this.Dispose(true) as per many other SO questions, but this complains that No overload for method 'Dispose' takes 1 arguments.

base.Dispoe() also does work, because of course 'SmtpClient' does not conatin a definition for 'Dispose'

Finally, I also tried the signature protected override void Dispose(bool disposing), but I get Dispose(): no suitable method found to override

Is anyone able to point me in the right direction with this?


Solution

  • 1 - you don't need to dispose anything, so you don't need Dispose.

    Just go for new:

    var client = new SmtpClient("mail.domain.com", 25)
    { Credentials = new NetworkCredential(), EnableSsl = false };
    
    client.Send(EmailAddress,
                EmailAddress,
                Subject,
                body);
    

    2 - If you really want to use using (and I don't know why you should), you have to implement an empty dispose (because you don't have anything to dispose to begin with):

    class DisposableSmtpClient : SmtpClient, IDisposable
    {
        public DisposableSmtpClient(string mailServer, int port) : base(mailServer, port)
        {
        }
    
        public void Dispose()
        {
            // anything to do, so don't do anything.
        }
    }
    

    IMO, KISS is a principle you should really consider.