0

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:

{
    DataReader dr = ...

    ...stuff involving data reader...
}

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

Mark Roworth
  • 409
  • 2
  • 15

2 Answers2

4

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);
    }
}
user18387401
  • 2,514
  • 1
  • 3
  • 8
  • Ah, so the scope of the using statement forces the disposal of the DataReader at the end of scope? I'd normally explicitly close a DataReader anyway, which is probably why it seems a bit superfluous. If I were to need several resources at the same time in this way, can I put multiple statements in side the brackets of the using statement, or would I need to nest multiple using statements? – Mark Roworth May 10 '22 at 10:38
  • You should use multiple using statements, however you can use the new using declaration which is available since C# 8: `using var obj = new DisposableType();` which will dispose it at the end of scope, which is usually end of the method. – misticos May 10 '22 at 10:41
  • @MarkRoworth, I have added some code examples that address your question. – user18387401 May 10 '22 at 10:44
  • @MarkRoworth But `using` handles exceptions also, which is precisely the point. – Charlieface May 10 '22 at 10:52
  • Super answer. Thank you. Completely get it now. – Mark Roworth May 10 '22 at 10:54
0

Such using statement automatically disposes the object obtained at the end of scope.

You may refer to this documentation for further details.

misticos
  • 718
  • 5
  • 22