How to find out the best place to use "use"?

I'm a little new to C #, more used to scripting languages. I like the idea of โ€‹โ€‹โ€œusingโ€, you create an instance of an object, and then you work within your scope, if you need it, then you let it control itself when it does its purpose.

But this is unnatural for me. When people show me usage examples, I think this is a good tool to work with, but it never occurred to me to solve problems with it in my own programming.

How can I recognize good places to use using and how to use it in combination with try-catch blocks. Do they go inside a block or do you usually want to enclose a using statement in a try block?

+7
c # using-statement
source share
11 answers

I rarely write a try / catch block - most exceptions get to the top of the stack (side by side). If I need a try / catch block, I am not sure that I particularly agree to put it in the using statement and outside of it. It depends on whether you want the resource to be deleted before your exception handling code runs.

If you ask when you should write using statements - every time you "own" an object that implements IDisposable (directly or indirectly through inheritance) and controls its lifetime. This is usually an object that uses an unmanaged resource, such as a file descriptor or network connection. This is not always very obvious, but you learn from your own experience. Almost everything related to IO will be one-time, and Windows descriptors (for fonts, etc.) are similar.

+9
source share

using can only be used with types that implement IDisposable ; it ensures that the Dispose() method is called even if an error occurs.

This code:

 using (MyDisposableType x = new MyDisposableType()) { // use x } 

equivalent to this:

 MyDisposableType x = new MyDisposableType(); try { // use x } finally { x.Dispose(); } 
+18
source share

I use it like "Use it every time the type implements IDisposable and you no longer need this particular instance."

+3
source share

If you want to know how to use it creatively in your own projects, check out some of your own codes for situations where a specific bit of code must be executed before exiting the closing block. These are situations where try / finally or using can help you.

In particular, if you tried to achieve this by catching all the exceptions, you really should change instead of try / finally or using .

If a template occurs multiple times, you can create a class that implements IDisposable to capture the template and allow you to call the template using the using statement. But if you have a specific case that seems one-time, just use try / finally .

Both are very similar, in fact - using is defined in terms of try / finally , but even if we had only using , we could build try / finally ourselves:

 public class DisposeAnything : IDisposable { public Action Disposer; public void Dispose() { Disposer(); } } 

Now you can say:

 using (new DisposeAnything { Disposer = () => File.Delete(tempFileName) }) { // blah } 

This is the same as:

 try { // blah } finally { File.Delete(tempFileName); } 

Just think of it as a way to get the code to execute when leaving the scope.

+2
source share

What Mitch said, plus ..

You can use the using statement inside or inside the try..catch block, which will really depend on what you are trying to achieve, that is, you reasonably expect something to throw an exception using one or another object that you plan to restore from , eg.

In addition, you can also delete an object that implements IDisposable in the finally block, if you need to.

+1
source share

Use when you need deterministic deletion of objects. For example, if you open a file, the file is locked. You often want the file to be closed as soon as possible so that other programs can access it. If you are not using smth use and notation, for example:

 System.IO.FileStream writeStream = new System.IO.FileStream( fileName, System.IO.FileMode.OpenOrCreate ) ); System.IO.BinaryWriter writer = new System.IO.BinaryWriter( writeStream ) ); //do smth 

and an exception occurs during "do smth", which you do not know when the objects working with the file are actually deleted and the file is closed. With the help of, you know for sure that after you leave the block of using statements, either directly or through an exception, the object in the usage statement will be deleted by calling IDisposable :: Dispose:

 using( System.IO.FileStream writeStream = new System.IO.FileStream( fileName, System.IO.FileMode.OpenOrCreate ) ) { using( System.IO.BinaryWriter writer = new System.IO.BinaryWriter( writeStream ) ) { //do stmth } } 
+1
source share

You can enclose use inside a try / catch block, and you can enclose a try / catch block inside used.

One of the situations where usage is good is when you perform database operations using DBConnection and DBCommands:

 using (SqlConnection conn = new SqlConnection(connectionString)) using (SqlCommand command = new SqlCommand(sql, conn)) { // do something here } 

Now that you leave the usage blocks, your team is located and the connection is closed.

+1
source share

What Mitch said is right. Thus, the main use is used to ensure that IDisposable objects are deleted without having to encode a try / catch or try / finally command.

You now have a more advanced use that may seem interesting to you. When you use the using statement, the compiler generates a try / finally, and also generates a Dispose () call for you inside the finally created one. You can use this Dispose () method as a hook to do whatever you want ... you don't have to relate to freeing resources.

For example, Jeffrey Richter uses this in the task of the timer that he wrote. You can do something similar with it (only conceptually):

 using(var x = new Timer()) { // Do the operation you want timed } // Now, the timer has been stopped, because the // compiler-generated call to Dispose() has already // occurred, and Jeffrey uses Dispose() to stop // the timer. 
+1
source share

If a class implements IDisposable, this is probably not without reason. Therefore, any class that implements IDisposable must be removed.

+1
source share

Given that this is what is called โ€œsyntactic sugarโ€ and will create the same IL as the try / finally dispose construct, this is really just a good way to โ€œpassโ€ such code shortly.

I like to use it to simplify sections of code where one-time objects are used a lot, i.e. access to resources such as files and graphic objects, and I want to make sure that I remember to process the disposal of the resource object.

+1
source share

I noticed that when the Dispose method is known to notice, so programmers do not bother to call it, as it seems pointless. However, if an object implements IDisposable (I hope) for some reason, and future versions of this object may actually have code in the Dispose method, so always call it.

0
source share

All Articles