0

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?

3
  • 2
    Dispose() does not reset the pointer to null. So the disposedChecker function does not work this way.. See below.. Commented Feb 10, 2014 at 8:40
  • so instead of null what should i use @JeroenvanLangen ? Commented Feb 10, 2014 at 8:41
  • Also, Disposing on StatementComplete looks a bit silly. After the command is complete, don't you want to handle the results of the command? Commented Feb 10, 2014 at 8:52

1 Answer 1

1

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....
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think in your code, StatementCompleted is not required.. as user is only disposing object here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.