Should reference-type members ever be marked readonly in a disposable class?

176 Views Asked by At

PROBLEM DESCRIPTION

  1. I have a class that implements IDisposable using accepted practices. See FooClass in the example below. I am using a string field for simplicity; try to imagine that this class has a legitimate reason for implementing IDisposable.
  2. FooClass initializes its own reference-type dependency, FooMember (not ideal, but assume it's necessary).
  3. FooMember is a read-only field.
  4. Normally I would set reference-type members to null during disposal. FooMember is read-only so I cannot. See the commented line in the example below.
  5. Per standards, I have instructed the garbage collector to suppress finalization of FooClass using GC.SuppressFinalize (see below).

QUESTIONS

  1. Will the garbage collector leave "foo" in memory after an instance of FooClass is disposed and out of scope?
  2. Should reference-type members ever be marked readonly in a disposable class?

EXAMPLE

public FooClass : IDisposable
{
    public FooClass()
    {
        FooMember = "foo";
    }

    public void Dispose()
    {
        if (IsDisposed)
        {
            return;
        }

        try
        {
            Dispose(true);
        }
        finally
        {
            IsDisposed = true;
            GC.SuppressFinalize(this);
        }
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // The line below won't compile because FooMember is read-only.
            // FooMember = null;
        }
    }

    private readonly string FooMember;
    private bool IsDisposed = false;
}
0

There are 0 best solutions below