Search code examples
.netfinalizer

Is it safe to access a reference type member variable in a finalizer?


In other words,

class Foo
{
    object obj;
    Foo() { obj = new object(); }
    ~Foo() { obj.ToString(); /* NullReferenceException? */ }
}

Solution

  • It's not safe since obj might have already been garbage collected. Also note that the garbage collector will not set the reference to null. So even checking for obj != null will not help you.

    See here for details: http://msdn.microsoft.com/en-us/magazine/cc163392.aspx#S3

    "Generalizing this principle, in a Dispose method it’s safe to clean up all resources that an object is holding onto, whether they are managed objects or native resources. However, in a finalizer it is only safe to clean up objects that are not finalizable, and generally the finalizer should only be releasing native resources." (Your obj is finalizable, so you shouldn't touch it in another finalizer)

    That's also the reason why you have the

    if (disposing) {...}

    in the IDisposable pattern (see Figure 2 in the link above).