1

I see it used and I read about it here and there and it has something to do with memory management. Question is, how do you know when you should use it? How do you tell the difference between variables or instances that will cause a problem if you don't use it?

Exact duplicate: What is the C# Using block and why should I use it?

Community
  • 1
  • 1
MetaGuru
  • 42,847
  • 67
  • 188
  • 294
  • http://stackoverflow.com/questions/212198/what-is-the-c-using-block-and-why-should-i-use-it Duplicate. – George Stocker Mar 24 '09 at 19:08
  • http://stackoverflow.com/questions/567138/when-should-i-use-using-blocks-in-c/568231 http://stackoverflow.com/questions/278902/using-statement-vs-try-finally http://stackoverflow.com/questions/614959/using-the-using-statment-in-c – George Stocker Mar 24 '09 at 19:09

3 Answers3

8

Whenever instantiating an object of a class that implements IDisposable.

Otávio Décio
  • 73,752
  • 17
  • 161
  • 228
1

The using statement is used with classes that implement IDisposable. The using statement provides a scope for the Disposable instance of the class and calls the Dispose method on the object when the scope is exited. You would implement IDisposable whenever you wanted to proactively release some managed resources or had unmanaged resources that need to be cleaned up when your managed object is garbage collected (or disposed).

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
0

it has something to do with memory management

Not really. It has to do with unmanaged resources: pretty much everything a computer can use except memory.

The problem is that you can't (okay: shouldn't) force the garbage collector to do clean up of your objects at specific times. However, with resources like database connections, sockets, semaphores, etc you don't want to hold on to them any longer than you have to. Normally you would have to use a try/finally construct. The using statement just provides a little nicer mechanism to handle this scenario. Reach for a using statement whenever you have any object that implements the IDisposable interface.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794