Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# What is the point of the using statement?

I’m not talking about references to assemblies, rather the using statement within the code.

For example what is the difference between this:

using (DataReader dr = .... )
{
    ...stuff involving data reader...
}

and this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    DataReader dr = ...

    ...stuff involving data reader...
}

Surely the DataReader is cleaned up by the garbage collector when it goes out of scope anyway?

>Solution :

The point of a using statement is that the object you create with the statement is implicitly disposed at the end of the block. In your second code snippet, the data reader never gets closed. It’s a way to ensure that disposable resources are not held onto any longer than required and will be released even if an exception is thrown. This:

using (var obj = new SomeDisposableType())
{
    // use obj here.
}

is functionally equivalent to this:

var obj = new SomeDisposableType();

try
{
    // use obj here.
}
finally
{
    obj.Dispose();
}

You can use the same scope for multiple disposable objects like so:

using (var obj1 = new SomeDisposableType())
using (var obj2 = new SomeOtherDisposableType())
{
    // use obj1 and obj2 here.
}

You only need to nest using blocks if you need to interleave other code, e.g.

var table = new DataTable();

using (var connection = new SqlConnection("connection string here"))
using (var command = new SqlCommand("SQL query here", connection))
{
    connection.Open();

    using (var reader = command.ExecuteReader()
    {
        table.Load(reader);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading