locked
Closing SqlDataReader using C# RRS feed

  • Question

  • User320184449 posted

    Do I need to close this SqlDataReader? From what I've read, using will close it automatically, is that true? I put a dr.Close() where I thought it should go but Visual Studio says it's unreachable.

                    using (SqlDataReader dr = cmd.ExecuteReader()) {
                        if (dr.HasRows) {
                            while (dr.Read()) {
                                Results.Add((string)dr["SearchTerm"]);
                            }
                            return Results.ToArray();
                        }
                        else { return null; }
                    }

    Wednesday, November 4, 2020 10:25 AM

Answers

  • User-821857111 posted

    No, you don't need to call Close() in this example. The using block ensures that is managed for you by the framework.

    If you did want to call Close, you would have to do so before the return statement.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 4, 2020 2:40 PM

All replies

  • User-821857111 posted

    No, you don't need to call Close() in this example. The using block ensures that is managed for you by the framework.

    If you did want to call Close, you would have to do so before the return statement.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 4, 2020 2:40 PM
  • User320184449 posted

    Thanks Mike..

    Wednesday, November 4, 2020 10:07 PM