Using-statement for disposable objects in C#

gpeipman
904 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
class DisposableDemoClass : IDisposable
{
public void Dispose()
{
Console.WriteLine("Dispose called!");
}
}
class Hello
{
static void Main()
{
var disp = new DisposableDemoClass();
disp.Dispose();
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
class DisposableDemoClass : IDisposable
{
public void Dispose()
{
Console.WriteLine("Dispose called!");
}
}
class Hello
{
static void Main()
{
using(var disp = new DisposableDemoClass())
{
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
class DisposableDemoClass : IDisposable
{
public void Dispose()
{
Console.WriteLine("Dispose called!");
}
}
class Hello
{
static void Main()
{
using(var disp1 = new DisposableDemoClass())
using(var disp2 = new DisposableDemoClass())
{
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content