Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I force the use of the 'using' statement for instances of my IDisposable class?

If my class (which in this case, takes care of database connections) implements IDisposable, is there a way I can force the use of of the using statement when instantiating my class? Or perhaps produce a compiler warning if this wasn't done?

eg:

MyDAL = new MyDal(); // Warns or errors
using (MyDAL = new MyDAL()) // Does not warn or error
like image 868
NickG Avatar asked Jan 28 '26 17:01

NickG


2 Answers

No, there's no language level support for this.

However, you may find that tools such as FxCop or ReSharper can warn about it. (You'd need to work out how to integrate that into your workflow.)

like image 159
Jon Skeet Avatar answered Jan 30 '26 07:01

Jon Skeet


Not at compile time, but you can make the finalizer throw an exception in debug mode.
That should tell you when the object wasn't disposed properly during debugging.

like image 39
user541686 Avatar answered Jan 30 '26 09:01

user541686



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!