Back
Close

Using-statement for disposable objects in C#

gpeipman
19.9K views

Using-statement

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

Manual disposing

This example shows how to dispose objects manually.

It's simple but in practice I have seen cases where developers forget to call Dispose() method when object is not needed anymore.

Disposing with using-block

We can make rule that disposable objects must be always defined within using-block like shown in the following example.

Now Dispose() is automatically called in the end of using-block.

Chaining using-blocks

It's possible to complaint now that code turns ugly when we nest one using-block inside another. This happens when we use some stream with stream reader and perhaps some specific reader that needs text reader. Good news is that using-blocks can conveniently be chained together like shown in the following example.

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io