Is the Use statement used?

Many people at SO have indicated that I should use the using statement more often. Therefore, I practice.

The problem is that I cannot decide when to use it and when not to use it. When I think I should use it, then I get errors like in this example (PS. HashPhrase is the class I created):

  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 recommendations on how to determine when a using statement should be used?

+6
source share
4 answers

Your question already addresses the answer.

If the type implements the IDisposable interface, you should use using whenever possible (i.e. always if there is no good reason).

And if the type does not implement IDisposable , you cannot use using , and the compiler will tell you about it, as you already discovered.

+14
source

You should use the using statement whenever a class implements the IDisposable interface.

This is a shorthand for wrapping an object in a try-finally block to ensure that the object Dispose method is always called to free any resources, regardless of whether an exception is thrown.

To verify, right-click the class name in Visual Studio and select "Go to declaration" to open it in Object Explorer. Then you can easily check if the class or its basic types implements IDisposable.

+4
source

IN

 using (var r = new R()) { // use r } 

class R must implement the IDisposing interface.

+4
source

The easiest way is to check if the object implements the IDisposable interface. So, right-click the object / class of interest, select "Go to Definition" in the drop-down list (or press F12) and see if the IDisposable class is implemented. Please note: in a class that implements many interfaces / other classes, you may need to actually check these classes to make sure they also implement IDisposable.

+2
source

Source: https://habr.com/ru/post/902889/


All Articles