How to ensure that the instantiation of a class is done only through "using"?

Asked

Viewed 80 times

2

I am creating a DLL with some database features (ADO.Net). It would be very convenient to ensure that instantiation of connections is always used only via using (block), not to forget to call the Dispose()/Close(). But it is also possible to forget to use the using.

How to ensure that the using is used in all classes with implementation of IDisposable?

  • The question was not very clear and I edited based on your comments, see if it got better.

2 answers

3

It is recommended to do so whenever a class implements the interface IDisposable. Unfortunately the compiler and even Visual Studio do not help to guarantee this. I even understand that the compiler does not oblige because there are rare legitimate cases that should not use this form.

But an additional configurable tool should help. Luckily there is Resharper that may alert you that whenever the class you are instantiating is not in a using. It’s the only way I know but others plugins its competitors must have something similar. Obviously the alert is only made for classes that implement the IDisposable.

It is also possible to customize the new .NET Compiler Platform to do this. I don’t have the data to tell you how to do this and it shouldn’t be too trivial, although it’s also not very complex. The idea of the new compiler platform is precisely to let people extend its operation according to their needs.

2


Just inside a using, nay.

The idea is that the Garbage Collector’s . NET is able to detect when an object will no longer be used within the context of the application, expiring and eliminating the object alone. Of course using the Dispose It’s much more elegant, but that can’t be required.

  • It may not have been clear, but the use of "just" in the question is in the sense of not allowing class instantiation if it is not by using block.

  • @Caiquec. I reworked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.