I'm trying to make a generic SQL call, which led me to an interesting question. I have a method that executes the SQL, and returns a SQLDataReader
.
private SqlDataReader ExecuteSql(SqlCommand command)
{
using (var connection = new SqlConnection(ConnectionText, Credentials))
{
command.Connection = connection;
connection.Open();
return command.ExecuteReader();
}
}
The calling command takes the reader and processes the returned data correctly. However, knowing that the reader needs to be disposed of, I enclosed it in a using
statement.
using (SqlDataReader reader = ExecuteSql(command))
{
while (reader.Read())
{
try { ... }
catch(Exception e) { ... }
}
}
I think Dispose
should be called on the SqlDataReader
at the end of the using
statement despite where in the code it was created. However, I have not been able to find anything that specifically confirms this.
Generalizing, can the using
statement be successfully used on an object that was created elsewhere in the code?
As a side note, I do realize that if the SqlDataReader
was created as an object in the ExecuteSql
method rather than returned directly, then there could be an issue with it throwing an exception while in the ExecuteSql
method and not being disposed of.