How can I place an IDisposable object if the using statement throws an exception?

How can I make sure of the following code fragment that IDataReader is deleted if ExecuteReader throws an exception?

 using (IDataReader rdr = cmd.ExecuteReader()) { // use it } 

It seems to me that syntactic sugar using does not call Dispose (since there is no instance to call it). However, how can I be sure that the scarce resources that are usually allocated by classes that implement IDisposable will be released?

+4
source share
4 answers

If the ExecuteReader, in your example, throws an exception, it never returns anything. Then, before implementing the ExecuteReader, everything that was created before the exception is deleted.

+14
source

If the constructor of the object does not start, then you do not have the object to be deleted.

If you are writing a constructor that can throw an exception, you better make sure that you clear everything you need with using or a try-catch block.

In your example, IDataReader simply needs to get rid of the command object if the call to cmd.ExecuteReader() method fails.

+3
source

How to move code that performs initialization outside the constructor into a separate function. Basically you will have

 using (var tc = new TestClass()) { tc.Initialize(); // setup the object. acquire expensive resources here, etc. ..more code .. } 
0
source

I thought the using statement was translated into IL, which is similar to:

 try { } finally { disposableUsedObject.Dispose(); } 

So, I think under normal circumstances, should Dispose be called?

In addition, you should not throw exceptions inside the constructor , since users will not expect that an exception will be thrown when creating an instance of the object. I would move the initialization logic, which could throw an exception from another method (Initialize), which should be called after creating an instance of the object.

-2
source

All Articles