Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know the best place to use 'using'?

I'm somewhat new to c#, more accustomed to scripting languages. I like the idea of 'using', you instantiate an object, and then you operate within its scope as long as you need it, then you let it dispose of itself when it's done its purpose.

But, it's not natural for me. When people show me examples using it, I recognize it as a good tool for the job, but it never occurs to me to solve problems with it in my own programming.

How can I recognize good places to use using and how do I use it in conjunction with try-catch blocks. Do they go inside the block, or do you usually want to enclose a using statement within a try block?

like image 696
danieltalsky Avatar asked Apr 03 '09 07:04

danieltalsky


1 Answers

using can only be used with types that implement IDisposable; it guarantees that the Dispose() method will be called even if an error occurs.

This code:

using (MyDisposableType x = new MyDisposableType())
{  
    // use x
}

is equivalent to this:

MyDisposableType x = new MyDisposableType();
try
{  
    // use x
}
finally 
{ 
    x.Dispose(); 
}
like image 112
Mitch Wheat Avatar answered Oct 01 '22 20:10

Mitch Wheat