Back
Close

Using-statement for disposable objects in C#

gpeipman
2,355 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.

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.

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.

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
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
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants