Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When Using statement should be used?

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?

like image 769
HelpNeeder Avatar asked Dec 02 '11 00:12

HelpNeeder


1 Answers

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.

like image 133
LukeH Avatar answered Sep 28 '22 10:09

LukeH