In other words,
class Foo
{
object obj;
Foo() { obj = new object(); }
~Foo() { obj.ToString(); /* NullReferenceException? */ }
}
In other words,
class Foo
{
object obj;
Foo() { obj = new object(); }
~Foo() { obj.ToString(); /* NullReferenceException? */ }
}
If this is a concern, then it's probably better to dispose than finalize.
From Object.Finalize:
The finalizers of two objects are not guaranteed to run in any specific order, even if one object refers to the other. That is, if Object A has a reference to Object B and both have finalizers, Object B might have already finalized when the finalizer of Object A starts.
In short, you can't make any assumptions about the state of referenced objects during a finalizer.
In virtually all circumstances, the logic implemented in a finalizer belongs in the Disposable pattern. This is an example of how to correctly implement the pattern in .NET using the IDisposable interface.
public class MyClass : IDisposable
{
private bool _disposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if(disposing)
{
// Release unmanaged resources.
}
// Release managed resources (Streams, SqlConnections, etc.)
}
_disposed = true;
}
}
In the unlikely event you're working with unmanaged resources, have a look at this article for how to implement IDisposable
with a finalizer:
MDSN: Implementing Finalize and Dispose to Clean Up Unmanaged Resources
In general, you don't want to implement finalizers on your objects. If you need to perform resource cleanup of managed objects, you want to do that in Dispose
and properly implement the Dispose pattern.
If you do end up implementing a finalizer, you only want to access unmanaged resources.