When Using statement should be used?

HelpNeeder picture HelpNeeder · Dec 2, 2011 · Viewed 12.5k times · Source

A lot of people on SO pointed out that I should use using statement more often. So I am practicing.

The problem is that I can't decide when to use it and when not to use it. When I think I should use it, then I get errors such as in this example (PS. HashPhrase is a class created by me):

        using (HashPhrase hash = new HashPhrase())
        {
            connection.ConnectionString =
                "Provider=Microsoft.ACE.OLEDB.12.0;" +
                "Data Source=" + filePath + ";" +
                "Persist Security Info=False;" +
                "Jet OLEDB:Database Password=" + hash.ShortHash(pass) + ";";
        }

But it gives me an error: 'Password_Manager.HashPhrase': type used in a using statement must be implicitly convertible to 'System.IDisposable'

But in this example it works fine:

    using (OleDbConnection connection = new OleDbConnection())
    {
        connection.ConnectionString =
            "Provider=Microsoft.ACE.OLEDB.12.0;" +
            "Data Source=" + filePath + ";" +
            "Persist Security Info=False;" +
            "Jet OLEDB:Database Password=" + hash.ShortHash(pass) + ";";

        using (OleDbCommand command = new OleDbCommand(sql, connection))
        {
            try
            {
                connection.Open();
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
        }
    }

Are there any quick guidelines how to determine when using statement should be used?

Answer

LukeH picture LukeH · Dec 2, 2011

Your question already touches on the answer.

If the type implements the IDisposable interface then you should aim to use using whenever possible (that is, always, unless there's a compelling reason not to).

And if the type doesn't implement IDisposable then you can't use using, and the compiler will tell you so, as you've already discovered.