Let’s say I have a class with a object field. When Dispose() is called I would like to clear the reference to that object. The private field can only be set once, so ideally I would like it to be readonly, but if it is readonly there is a compile time error when I try to release the reference to the object during Dispose(). Ideally I would like to have a safe dispose AND mark the _value field as readonly. Is this possible or even necessary?
public class Foo : IDisposable
{
public Foo(object value)
{
_value = value;
}
public object Value { get { return _value; } }
private readonly object _value;
public void Dispose()
{
//Cleanup here
_value = null // causes compile time error
}
}
That’s not necessary, even if it were possible.
Dispose is typically intended to clean up unmanaged resources, although there can be exceptions to that rule (note the comments). However, in this situation, you should allow the garbage collector to do its job. It will run indeterminately once the objects are considered to have no active roots. Under normal circumstances, you do not need to take action to force it. Just write your code with objects in properly limited scope and you will be fine.