The difference between β€œuse” and scope?

What is the difference between the following two pieces of code:

using (Object o = new Object()) { // Do something } 

and

 { Object o = new Object(); // Do something } 

I started using using lot more, but I'm curious what the actual benefits are compared to objects with scope.

Edit: Useful tidbits I took from this:

John Skeet:

Please note that this does not force garbage collection in any way, form or form. Garbage collection and timely cleaning of resources are somewhat orthogonal.

Will Eddin comment:

If your class does not implement the IDisposable interface and does not have the Dispose () function, you are not using it.

+7
scope c # using
source share
5 answers

The first fragment calls Dispose at the end of the block - you can only do this with types that implement IDisposable , and it basically calls Dispose in the finally block, so you can use it with types that require resource cleaning, for example

 using (TextReader reader = File.OpenText("test.txt")) { // Use reader to read the file } // reader will be disposed, so file handle released 

Please note that this does not force garbage collection in any way, form or form. Garbage collection and timely cleaning of resources are somewhat orthogonal.

Basically, you should use the using statement for almost everything that implements IDisposable and that your code block will be responsible (in terms of cleanup).

+20
source share

At the end, using object will be deleted (the object that you put inside the brackets must implement IDisposable). The object also falls into exceptions. And you don’t have to wait for the GC to do this at some time (you control it).

EDIT: Lack of scope:

  • you do not control the location of the object
  • even if you call the dispose command at the end of your scope, this will not be a safe exception
+3
source share

Just to literally show the difference ...

 using (FileStream fileStream = new FileStream("log.txt", FileMode.OpenCreate)) { //stuff with file stream } 

matches with ...

 { FileStream fileStream = new FileStream("log.txt", FileMode.OpenCreate); try { //stuff with filestream } finally { if (fileStream != null) ((IDisposable)fileStream).Dispose(); } } 

where as

 { FileStream fileStream = new FileStream("log.txt", FileMode.OpenCreate); fileStream.Dispose(); } 

as it is.

+3
source share

See the documentation for IDisposable and defined resource release.

Simply put, at the end of the using{} block, you can reliably manage allocated resources (for example, close file descriptors, database connections, etc.).

+1
source share

using just requires an implementation of the IDisposable interface and calls the Dispose method at the end of the scope.

For a lot of the fury of arguments about the correct removal of objects, there are many other threads.

0
source share

All Articles