PROBLEM DESCRIPTION
- I have a class that implements
IDisposableusing accepted practices. SeeFooClassin the example below. I am using astringfield for simplicity; try to imagine that this class has a legitimate reason for implementingIDisposable. FooClassinitializes its own reference-type dependency,FooMember(not ideal, but assume it's necessary).FooMemberis a read-only field.- Normally I would set reference-type members to
nullduring disposal.FooMemberis read-only so I cannot. See the commented line in the example below. - Per standards, I have instructed the garbage collector to suppress finalization of
FooClassusingGC.SuppressFinalize(see below).
QUESTIONS
- Will the garbage collector leave
"foo"in memory after an instance ofFooClassis disposed and out of scope? - Should reference-type members ever be marked
readonlyin 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;
}