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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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):
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.