Search code examples
.netidisposablefinalizer

Forcing Dispose() while debugging


I know it isn't standard practice, but are there any downsides or better alternatives to doing the following? I just want to make sure the code is being used properly, and .NET doesn't do anything for you to ensure it.

public class MyClass : IDisposable
        public void Dispose()
        {
            // Some managed shutdown logic...
            GC.SuppressFinalize(this);
        }

#if DEBUG
        // Why is ConditionalAttribute not allowed if you can still achieve this with compiler directives?
        // [Conditional("DEBUG")]
        ~SFtpClient()
        {
            Debug.Fail("This class is IDisposable and should be wrapped by using {}");
        }
#endif
}

Solution

  • It looks good to me because that conditional will prevent the un-necessary Finalizing cost of an empty Finalizer in RELEASE builds. Might want to add the #if DEBUG around the GC.SupressFinalize, too.

    The [Conditional("DEBUG")] tells the compiler not to call the method, but the method is still there. You can't compile a call the Finalize() method, anyway. The GC Finalizer doesn't check the attribute.