PROBLEM DESCRIPTION
- I have a class that implements
IDisposable
using accepted practices. SeeFooClass
in the example below. I am using astring
field for simplicity; try to imagine that this class has a legitimate reason for implementingIDisposable
. FooClass
initializes its own reference-type dependency,FooMember
(not ideal, but assume it's necessary).FooMember
is a read-only field.- 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. - Per standards, I have instructed the garbage collector to suppress finalization of
FooClass
usingGC.SuppressFinalize
(see below).
QUESTIONS
- Will the garbage collector leave
"foo"
in memory after an instance ofFooClass
is disposed and out of scope? - 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;
}