What is the purpose of use?

DUPE: Using "using" in C #

I have seen people use the following, and I wonder what is its purpose? Is it really so that an object is destroyed after its use by garbage collection?

Example:

using (Something mySomething = new Something()) {
  mySomething.someProp = "Hey";
}
+5
source share
6 answers

Use translates, roughly speaking, into:

Something mySomething = new Something();
try
{
  something.someProp = "Hey";
}
finally
{
  if(mySomething != null)
  {
    mySomething.Dispose();
  }
}

And that is pretty much the case. The goal is to support deterministic deletion, something that C # does not have, because it is a garbage collection. Data usage / deletion patterns give programmers the ability to specify exactly when a type cleans up its resources.

+6
source

using , Dispose() , , .

+4

using , (), .

+2

using, Something IDisposable. , using.

.. Dispose, using .

:

Something mySomething = new Something();
try
{
   // this is what inside your using block
}
finally
{
    if (mySomething != null)
    {
        mySomething.Dispose();
    }
}
+2

try
{
   ...
}
finally
{
   myObj.Dispose();
}

( IL).

, , IDisposable.

+1

The use block is a way to ensure that the object's dispose method is called when the block is exited.

This is useful because you can exit this block normally because of interruptions, because you came back or because of an exception.

You can do the same with try / finally, but using uses simplifies what you mean and does not require a variable declared outside the th block.

0
source

All Articles