How can I use IDisposable in a class derived from a class that's implementing IDisposable already?

AxD 671 Reputation points
2021-02-03T00:15:00.963+00:00

I'm trying to understand how Finalizers and IDisposable are supposed relate to each other in a class hierarchy.

Given I have a class that's deriving from a base class, both classes have unmanaged resources. How would I implement Finalizers and IDisposable in both?

For this hypothetical question, let's assume I want to derive a class from System.IO.FileStream. The derived class will manage a separate log file that's supposed to be flushed and closed when either Dispose() is called on the derived class or the class is getting finalized.

How would I implement these two classes for the following code to work:

{
  using FileStream myObj = new MyDerivedLoggerClass(...);
}


{
  FileStream myObj = new MyDerivedLoggerClass(...);
}

I would expect the derived class to look similar to this:

using System;
using System.IO;

namespace FinalizeTest
{
  public class DerivedClass : FileStream, IDisposable
  {
    private StreamWriter _logFile;


    public DerivedClass(string path, FileMode mode) : base(path, mode)
    {
      _logFile = new StreamWriter(path + ".log");
    }

    ~DerivedClass() => Dispose(false);

    public new void Dispose() => Dispose(true);

    public new void Dispose(bool isDisposing)
    {
      base.Dispose(isDisposing);

      _logFile?.Close();
      _logFile = null;
    }
  }
}

But would this work if the variable is declared as the base class type?

Developer technologies | .NET | .NET Runtime
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. AxD 671 Reputation points
    2021-02-03T00:24:10.707+00:00

    OK, I did some debugging, and I noticed that the derived Dispose() methods are called, regardless of variable declaration.

    Everything is clear now.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.