Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to enforce the use of a using statement in C#

Tags:

c#

using

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?

like image 273
Bigtoe Avatar asked Apr 15 '09 10:04

Bigtoe


1 Answers

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.

like image 113
Jon Skeet Avatar answered Oct 25 '22 05:10

Jon Skeet