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(); }
Using-blocks are convenient way to automatically dispose objects that implement IDisposable interface to release resources that garbage collection cannot automatically manage.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With