7

What does this statement means in C#?

        using (object obj = new object())
        {
            //random stuff
        }
Michael Meadows
  • 27,796
  • 4
  • 47
  • 63
Ricardo
  • 11,609
  • 8
  • 27
  • 39

5 Answers5

12

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();
    }
  }
}
Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • 2
    Almost right, using() doesn't imply a catch statement, only try/finally. – Turnor Jan 12 '10 at 18:43
  • @Jay Zeng, as in Graphics? If i use my Graphics inside a "using" statement i wont need to dispose? – Ricardo Jan 12 '10 at 18:47
  • 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 Jan 12 '10 at 18:48
  • 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 Jan 12 '10 at 20:41
5
using (object obj = new object())
{
    //random stuff
}

Is equivalent to:

object obj = new object();
try 
{
    // random stuff
}
finally {
   ((IDisposable)obj).Dispose();
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 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 Cudmore Jan 12 '10 at 18:51
1

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
  • 48,078
  • 23
  • 82
  • 145
  • 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 idiom also I was trying to explain why you see it used - and why you would see the non sugar version – pm100 Jan 12 '10 at 23:46
0

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
  • 6,081
  • 1
  • 26
  • 39
0

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

Johannes Rudolph
  • 35,298
  • 14
  • 114
  • 172