The IDISP023 rule prevents the use of reference types within a finalizer context.
Why this is important
Accessing reference types during finalization is hazardous, especially during AppDomain shutdown. The CLR does not guarantee the order of finalization or garbage collection, meaning any reference type access could result in an access violation and process crash.
Safe activities in a finalizer are limited to:
- Accessing value types.
- Calling P/Invoke methods (native code) to release resources.
Note: Even accessing SafeHandle is considered unsafe because SafeHandle types have their own finalizers and should not be relied upon by their owners during finalization.
How to fix violations
Ensure that any access to reference types is wrapped within a check for the disposing parameter (typically found in the Dispose(bool disposing) pattern), which ensures the code only runs when called via explicit disposal rather than the finalizer.
// Invalid: Accessing a reference type (logger) outside the 'if (disposing)' block
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
}
this.logger.Log("In Dispose(bool)"); // violation!
}
// Valid: Accessing the reference type only when 'disposing' is true
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.logger.Log("In Dispose(bool)");
}
}