OK, I did some debugging, and I noticed that the derived Dispose()
methods are called, regardless of variable declaration.
Everything is clear now.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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?
OK, I did some debugging, and I noticed that the derived Dispose()
methods are called, regardless of variable declaration.
Everything is clear now.