views:

236

answers:

5

What does this statement means in C#?

        using (object obj = new object())
        {
            //random stuff
        }
+12  A: 

It means that obj implements IDisposible and will be properly disposed of after the using block. It's functionally the same as:

{
  //Assumes SomeObject implements IDisposable
  SomeObject obj = new SomeObject();
  try
  {
    // Do more stuff here.       
  }
  finally
  { 
    if (obj != null)
    {
      ((IDisposable)obj).Dispose();
    }
  }
}
Justin Niessner
oh! Nice! Thanks for the reply.
Ricardo
Almost right, using() doesn't imply a catch statement, only try/finally.
Turnor
@Jay Zeng, as in Graphics? If i use my Graphics inside a "using" statement i wont need to dispose?
Ricardo
And the compiler inserts a check to ensure that the value is not null if the variable is of a nullable type.
Daniel Brückner
No one mentioned that it also "touches" the object at the close brace by calling the .Dispose method. This means that the garbage collector will not touch to object till after the .Dispose()
Spence
+5  A: 
using (object obj = new object())
{
    //random stuff
}

Is equivalent to:

object obj = new object();
try 
{
    // random stuff
}
finally {
   ((IDisposable)obj).Dispose();
}
Darin Dimitrov
Almost equivalent. In the first sample obj is out of scope at the }. In the second, it is still in scope. Similar to the for-while equivalence.
chris
A: 

it is a way to scope an object so the dispose method is called on exit. It is very useful for database connections in particuler. a compile time error will occur if the object does not implement idisposable

Pharabus
A: 

using ensures the allocated object is properly disposed after the using block, even when an unhandled exception occurs in the block.

Johannes Rudolph
+1  A: 

why does it exist tho.

It exists for classes where you care about their lifetime, in particular where the class wraps a resource in the OS and you want to release it immediately. Otherwise you would have to wait for the CLR's (non deterministic) finalizers.

Examples, file handles, DB connections, socket connections, ....

pm100
It is syntactical sugar
BlueRaja - Danny Pflughoeft
i disagree - it is a well known pattern and so encourages common good practice. for loop is syntactical sugar too - but it is always used becuase it is a common idiomalso I was trying to explain why you see it used - and why you would see the non sugar version
pm100