Does using statement close all kinds of streams in it?

46 views Asked by At

I have using statement to close the OleDbConnection and then I'm working with the reader. I'm wondering if I have to close the reader at the end or I can rely on the using statement to close it.

I've got the following code:

string connectionString = @"Some connection"; 
using (OleDbConnection connection = new OleDbConnection(connectionString)) 
{ 
    string query = "SELECT ID, Name, \[Position\] FROM Players"; 
    OleDbCommand command = new OleDbCommand(query, connection); 
    connection.Open(); 
    OleDbDataReader reader = command.ExecuteReader(); 

    while (reader.Read()) 
    { 
        Console.WriteLine($"ID.{reader\[0\]} {reader\[1\],-18}{reader\[2\]}"); 
    } 
    reader.Close(); 
}
1

There are 1 answers

2
Tim Schmelter On

As a rule of thumb:

Use the using-statement for everything that implements IDisposable.

So yes, use the using also for the OleDbDataReader and the OleDbCommand.

But you can simplify all to this:

using var connection = new OleDbConnection(@"Some connection");
using var command = new OleDbCommand("SELECT ID, Name, Position FROM Players", connection);
connection.Open();
using OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
    Console.WriteLine($"ID.{reader[0]} {reader[1],-18}{reader[2]}");
}