tags:

views:

185

answers:

3

Would really like to be able to decorate my class with an attribute of some sort that would enforce the use of a using statement so that the class will always be safely disposed and avoid memory leaks. Anyone know of such a technique?

+4  A: 

You could use FxCop to enforce this rule. See the Wikipedia for a quick overview.

Daniel Brückner
Doesn't help when people are *using* his classes - he can't tell his users to use FxCop
ChrisF
Good point. But this is their problem ... :D
Daniel Brückner
Make it a part of the build and they have to pay attention to it.
Michael Hedgpeth
+10  A: 

Well, there's one way you could sort of do it - only allow access to your object via a static method which takes a delegate. As a very much simplified example (as obviously there are many different ways of opening a file - read/write etc):

public static void WorkWithFile(string filename, Action<FileStream> action)
{
    using (FileStream stream = File.OpenRead(filename))
    {
        action(stream);
    }
}

If the only things capable of creating an instance of your disposable object are methods within your own class, you can make sure they get used appropriately. Admittedly there's nothing to stop the delegate from taking a copy of the reference and trying to use it later, but that's not quite the same problem.

This technique severely limits what you can do with your object, of course - but in some cases it may be useful.

Jon Skeet
I felt a bit dirty doing something similar to this. *feels better now it has Skeet endorsement*
Andrew Bullock
This isn't a "new" pattern by any means - not that I can remember the name right now...
Jon Skeet
A: 

If you want to ensure your object is always disposed, use a finalizer in combination with IDisposable.

But before you do, read up on IDisposable and finalizers, and be conscious of the fact that you normally don't need them unless your class is doing something like managing the lifetime of an unmanaged resource.

With a finalizer your object will be reclaimed 'eventually' whether wrapped in a using or not. The using statement, which is a convenience for IDisposable, allows deterministic cleanup to take place. The only caveat is that object with finalizers are more expensive to clean up and in general stick around in memory longer while they await finalization.

ref When do I need to implement a finalizer or IDisposable? or technorabble: Using Dispose, Finalizers and IDisposable

Robert Paulson