Search code examples
c#npgsql

How do you use just "using" for npgsql instead of trycatchfinally?


In one of my previous questions someone suggested that instead of using trycatch and closing the connection at finally I should just use "using". Can someone give me an example?

I have this code, how do I use just "using" with it?

            try
            {
                conn3.Open();
                string sql_check = "SELECT (time_in) FROM timeinout WHERE employee_id = @employee_id AND date = @date";
                using var cmd_check = new NpgsqlCommand(sql_check, conn3);

                cmd_check.Parameters.AddWithValue("employee_id", id);
                cmd_check.Parameters.AddWithValue("date", date);
                cmd_check.Prepare();

                var reader = cmd_check.ExecuteReader();

                if (reader.Read())
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
            catch
            {
                return false;
            }
            finally
            {
                conn3.Close();
            }

Solution

  • using is not a replacement for try...catch...finally. It enables you to do away with the finally block but, if an exception can be thrown, you still need to catch it. The using block guarantees that the object created will be disposed, whether an exception is thrown or not. This:

    var obj = new SomeType();
    
    try
    {
        // Use obj here.
    }
    catch
    {
        // Handle exception here.
    }
    finally
    {
        obj.Dispose();
    }
    

    can AND SHOULD be replaced with this:

    using (obj = new SomeType())
    {
        try
        {
            // Use obj here.
        }
        catch
        {
            // Handle exception here.
        }
    }
    

    Basically, if already have exception handling then you still need exception handling but you don't need to close/dispose locally-created objects in a finally block. If you're doing anything else in your finally block then you still need it too.

    In your case, you should be creating your connection, command and data reader with using statements:

    using (var connection = new NpgsqlConnection(connectionString))
    using (var command = new NpgsqlCommand(query, connection))
    {
        try
        {
            connection.Open();
    
            using (var reader = command.ExecuteReader())
            {
                return reader.HasRows;
            }
        }
        catch
        {
            return false;
        }
    }
    

    The data reader will be closed at the end of the inner using block and the connection will be closed at the end of the outer using block.