Is it possible to force the use of using using operator in C #

I would like to be able to decorate my class with some attribute that will ensure the use of the operator, so that the class is always safely deleted and avoids memory leaks. Does anyone know such a technique?

+6
c # using
source share
3 answers

Well, thereโ€™s one way you could do this - only allow access to your object through the static method that the delegate accepts. As a very simplified example (since, obviously, there are many different ways to open 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 that can instantiate your one-time object are methods in your own class, you can make sure that they are used appropriately. Admittedly, nothing prevents the delegate from taking a copy of the link and trying to use it later, but this is not exactly the same problem.

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

+13
source share

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

+5
source share

If you want your object to always be located, use the finalizer in combination with IDisposable.

But before you do this, read IDisposable and finalizers and be aware of what you usually don't need unless your class does something like managing the lifetime of an unmanaged resource.

With a finalizer, your object will be returned "in the end", whether in use or not. The using statement, which is a convenience for IDisposable, allows deterministic cleaning. The only caveat is that an object with finalizers is more expensive to clean up and, in general, lingers in memory longer while they wait for completion.

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

0
source share

All Articles