Search code examples
c#.netreturnidisposableusing

Return value from USING statement


Originally this method returns false only in case of ANY problems regardless of their type. I'm wondering will applying using statement break the logic if exception

Is it ok to return true value from the using statement in this manner:

    try
    {

        Measurements.DeleteAllMeasurements(ID);
        string query = "DELETE FROM `Narz` WHERE `NAZk_1_ID`=@NAZ_ID";
        using(OleDbConnection strukturaConnection = new OleDbConnection(CommonConnectionString + DbPath + strStructureMdb))
            {
                using (OleDbCommand command = new OleDbCommand(query, strukturaConnection);)
                    {

                        command.Parameters.Add("@NAZ_ID", OleDbType.Numeric, 50);
                        command.Parameters["@NAZ_ID"].Value = ID;
                        command.ExecuteNonQuery();
                        return true; 
                    } 
            }
    }
    catch (Exception ex)
    {
        Logger.LogError(ex);
        return false;
    }

Or I should return false in another way?


Solution

  • All the using statement does is implicitly call the instance's implementation of IDisposable.Dispose() at the end of the code block.

    Unless you are returning a reference and the Dispose() method happens to manipulate it, then the two concerns are completely unrelated.

    In short, it doesn't matter what value you return from within a using statement.

    Edit: About what your method "should return": We don't have enough information to know this. We don't even know what the name of the method is. And we don't know by what other objects or aspects of the application the method will be used. The return value should be meaningful to its caller, and effectively communicate the result of the operation.