Is there a reason to check for null in the last using? Seems to me like it’s most likely not gonna be needed?
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(commandString, connection))
{
using (var reader = command.ExecuteReader())
{
if (reader != null) {
// Use the reader
}
}
}
}
EDIT:
Should i close reader.Close() and connection.Close() inside the using if i use it like that:
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetailsDZP))
using (var sqlWrite = new SqlCommand(preparedCommand, varConnection)) {
while (sqlWrite.Read()) {
//something to do.
}
sqlWrite.Close();
varConnection.Close();
}
public static SqlConnection sqlConnectOneTime(string varSqlConnectionDetails) {
SqlConnection sqlConnection = new SqlConnection(varSqlConnectionDetails);
sqlConnect(sqlConnection);
if (sqlConnection.State == ConnectionState.Open) {
return sqlConnection;
}
return null;
}
Is using of close necessary in following example or i can skip those two?
sqlWrite.Close();
varConnection.Close();
With regards,
MadBoy
No, this is not necessary.
But that follows from the definition of
ExecuteReader, it is not related to the using clause.ExecuteReadereither returns a (non-null) DataReader object or it throws an exception.The expresion in the
ifstatement will always be true (if it is reached).And by leaving out the
ifand all the superfluous brace-pairs you can make this much easier to read: