views:

536

answers:

4

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?

+1  A: 

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

x0n
Could you explain the "not guaranteed to be called by the GC" ?
Henk Holterman
During program termination, some objects might not get a chance to run their finalizers if cleanup takes too long. That could be what he's referring to.
Lasse V. Karlsen
Yes, that's what I was referring to.
x0n
+4  A: 

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.

If you're implementing IDisposable, you should prevent this from running, since in theory you're doing the cleanup already.

Reed Copsey
True. Also, you should have a finalizer that calls Dispose().
configurator
True and False: objects are by default not put on the Finalizer list. In C# you need to add a dtor to get that. The Finalize in System.Object is just an interface point.
Henk Holterman
True- Object.Finalize is a null op., but if you're implementing IDisposable, you're saying you have resources to free up. From MSDN, that means you should always have a finalizer to free them, so they're handled correctly. This means having Finalize call Dispose, and Dispose suppress finalization
Reed Copsey
+1  A: 

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.

cxfx
If an object is "responsible" for other, IDisposable, objects but has no unmanaged resources by itself then it needs Dispose but no Finalizer.
Henk Holterman
+6  A: 

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.

Lasse V. Karlsen