Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does "using" statement always dispose the object?

Does the using statement always dispose the object, even if there is a return or an exception is thrown inside it? I.E.:

using (var myClassInstance = new MyClass()) {     // ...     return; } 

or

using (var myClassInstance = new MyClass()) {     // ...     throw new UnexplainedAndAnnoyingException(); } 
like image 415
Guillermo Gutiérrez Avatar asked Jun 28 '13 04:06

Guillermo Gutiérrez


People also ask

Does using statement automatically Dispose?

Using-blocks are convenient way to automatically dispose objects that implement IDisposable interface to release resources that garbage collection cannot automatically manage.

What is special about the using statement?

The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.

Does using Dispose if exception?

MSDN using documentation also confirms this answer: The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.

Which statement describes a Dispose method?

C# provides a special "using" statement to call Dispose method explicitly. using statement gives you a proper way to call the Dispose method on the object. In using statement, we instantiate an object in the statement. At the end of using statement block, it automatically calls the Dispose method.


Video Answer


1 Answers

Yes, that's the whole point. It compiles down to:

SomeDisposableType obj = new SomeDisposableType(); try {     // use obj } finally {     if (obj != null)          ((IDisposable)obj).Dispose(); } 

Be careful about your terminology here; the object itself is not deallocated. The Dispose() method is called and, typically, unmanaged resources are released.

like image 190
Ed S. Avatar answered Sep 24 '22 08:09

Ed S.