Using-statement for disposable objects in C#

gpeipman
20.3K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content