Hello, HashCode, I have a question, I wrote this code

private void GetSettings() { using (MySqlConnection cnt = new MySqlConnection(sql.strProvider)) { MySqlCommand cmd = cnt.CreateCommand(); cmd.CommandText = "SELECT * FROM t_settings"; try { cnt.Open(); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { variable.wmrAdmin = reader["WMR"].ToString(); variable.datastart = reader["STARTDATE"].ToString(); } reader.Close(); } catch (MySqlException ee) { log.WriteError(ee.Message); } } } 

So, in this code there is a try ... catch block, and it is not entirely clear whether it is worth adding a block here.

 finally { cnt.Close(); } 
  • one
    No, the compiler will do it for you - Specter

1 answer 1

  • For cnt - not necessary, but for the reader - necessary.

  • If the Read() function throws an exception, the reader will not be closed. That is, reader.Close() should be located in the finally block.

  • 3
    or wrap the reader with an operator using - Specter