Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

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

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