How generally it is more correct to arrange return / false blocks in the following code block:

public bool CheckIfDBIsExists() // selecting from pg_database and checking if DB from config is exists { NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=" + config.PGLogin + ";" + "Password=" + config.PGPass + ";"); try { conn.Open(); Console.WriteLine("PG Connected"); string getlistofDBs = @"SELECT datname FROM pg_database; "; NpgsqlCommand command = new NpgsqlCommand(getlistofDBs, conn); try { List<string> DBList = new List<string>(); NpgsqlDataReader dr = command.ExecuteReader(); while (dr.Read()) { DBList.Add(dr[0].ToString()); } foreach (var db in DBList) { Console.WriteLine("List of DBs:"); Console.WriteLine(db); } if (DBList.Contains(config.PGdbName)) { return true; // ? } else { return false; // ? } } finally { conn.Close(); } } catch (SocketException e) { Console.WriteLine(e.Message); } finally { conn.Close(); } } 

In theory, if the condition DBList.Contains(config.PGdbName) true, then we need to return true , but the question is how to deal with false? Should I return false into each catch and do I need a return in the finally block?

  • return inside finally Can't - Grundy

2 answers 2

If true in one place, and false for any other outcomes, then a return can be made at the end of the method, since if the control reached this operator, then it did not reach return true .

 public bool CheckIfDBIsExists() { ... return false; } 

    Put return false; in the end:

      if (DBList.Contains(config.PGdbName)) { return true; } ... } finally { conn.Close(); } return false; }