Search code examples
c#disposesqlcommand

How can I possibly know if SQLcommand is properly disposed?


How can I possibly know if SQLcommand is properly disposed?

My problem is that my code always returns false because my sqlcommand is not equivalent to null

How can I possibly fix this issue?

Here is my code:

private SqlCommand Command()
    {
        cmd = new SqlCommand(QueryStr, Connection);
        cmd.StatementCompleted += new StatementCompletedEventHandler(cmd_StatementCompleted);
        return cmd;
    }

    private void cmd_StatementCompleted(object sender, StatementCompletedEventArgs e)
    {
        ((SqlCommand)sender).Dispose();
    }

    public object GetScalarResult()
    {
        Command();

        cmd.CommandType = CommandType;

        con.Open();

        return cmd.ExecuteScalar();
    }

    public bool IsDisposedChecker()
    {
        if (cmd == null)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

My IsDisposedChecker function always returns false so that means sqlcommand is not properly disposed?


Solution

  • Dispose() does not reset the pointer to null. So the ISDisposedChecker function does not work this way..

    Dispose isn't a destructor..


    I wouldn't implement a dispose-checker, I would put the Dispose responsibility to the caller method if you want to return the SqlCommand as result.

    private SqlCommand Command()
    {
        cmd = new SqlCommand(QueryStr, Connection);
        return cmd;
    }
    
    private void Test()
    {
        // a using block is very safe, it will dispose the command 
        // even when exceptions are thrown.
        using(SqlCommand command = Command())
        {
            // do your thing....
        }
    }