6

If I have the following, will IDisposeable still be called on DisposeableObject, or will the object remain opened because an un-handled exception is encountered?

using ( DisposeableObject = new Object() )
{
   throw new Exception("test");
}
ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
Judas
  • 73
  • 2
  • Possible duplicate of http://stackoverflow.com/questions/1404769/when-would-dispose-method-not-get-called – SRM Nov 24 '10 at 20:52

5 Answers5

5

A using is like wrapping your code in a try...finally and disposing in the finally, so yes, it should be called.

Mike Dour
  • 3,616
  • 2
  • 22
  • 24
2

using expands to a try..finally block, so yes, it will call Dispose.

Michael Stum
  • 177,530
  • 117
  • 400
  • 535
2

In the example you provided Dispose will be called before the exception is thrown.

The normal code for ensuring that dispose gets called looks like

var connection= new SqlConnection(connectionString);
try
{
  // do something with the connection here
}
finally
{
  connection.Dispose();
}

The usings statement replaces the need to write such a cumbersome statement.

using(var connection = new SqlConnection(connectionString))
{
  // do something with the connection here
}
Rohan West
  • 9,262
  • 3
  • 37
  • 64
0

According to MSDN, yes. When control leaves the scope of the using statement, expect it to be disposed.

David
  • 208,112
  • 36
  • 198
  • 279
0

The object will be disposed as you will come out of scope when the exception bubbles up.

See: using Statement (C# Reference)

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

Will Marcouiller
  • 23,773
  • 22
  • 96
  • 162