Wednesday, July 22, 2015

You are implementing IDisposable correctly, right?

I'm trying to fix some code issues suggested by NDepend, in order to get super-sweet high quality code ( at least, that's what I'm striving for ). As it turns out, I hadn't implemented IDisposable on two classes that are using Memcache. 
NDepend pointed that out for me, so I made them implement IDisposable. I always google 'basic dispose pattern' to make sure I do it correctly but I always forget why you have to do it the way it's described on this page. 

Here's why the Dispose() method calls another Dispose method in the pattern:

The Boolean parameter disposing indicates whether the method was invoked from the IDisposable.Dispose implementation or from the finalizer. The Dispose(bool) implementation should check the parameter before accessing other reference objects (e.g., the resource field in the preceding sample). Such objects should only be accessed when the method is called from the IDisposable.Dispose implementation (when the disposing parameter is equal to true). If the method is invoked from the finalizer (disposing is false), other objects should not be accessed. The reason is that objects are finalized in an unpredictable order and so they, or any of their dependencies, might already have been finalized.

More information here:

And of course - there's a whole course about it on PluralSight:

No comments:

Post a Comment