Question

For some reason FXCop seems to think I should be calling GC.SuppressFinalize in Dispose, regardless of whether I have a finalizer or not.

Am I missing something? Is there a reason to call GC.SuppressFinalize on objects that have no finalizer defined?

Was it helpful?

Solution

There is always a finalizer in IL - System.Object.Finalize() exists in every class, so if you make a custom class, it has a finalizer you want to suppress. That being said, not all objects are put on the finalization queue, so you only techncially should need to suppress finalization if you implement your own finalizer.

If you're implementing IDisposable to wrap unmanaged resources, you should include a finalizer, and you should prevent this from running, since in theory you're doing the cleanup already when Dispose is called.

OTHER TIPS

There's no need to call GC.SuppressFinalize(this) in Dispose, unless:

  • You are the base class that implements virtual Dispose methods intended for overriding (again, it might not be your responsibility even here, but you might want to do it in that case)
  • You have a finalizer yourself. Technically, every class in .NET has a finalizer, but if the only finalizer present is the one in Object, then the object is not considered to need finalizing and isn't put on the finalization list upon GC

I would say, assuming you don't have any of the above cases, that you can safely ignore that message.

All objects have a finalizer method, even if you have not implemented one by using a c# destructor (which is not actually guaranteed to be called by the GC). It's just good practice to supress the call if you have implemented IDisposable because that means you have decided to perform the finalization explictly.

devx article

I don't see any need to call SuppressFinalize() if there's no finalizer defined. If you want to be defensive then it can be good to have a finalizer as well as Dispose(), so you don't need to rely on clients to always call Dispose(). Then you won't leak resources when they forget.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top