When should I use “using” blocks in C#?

http://stackoverflow.com/questions/567138/when-should-i-use-using-blocks-in-c

When the SomeType class implements IDisposable.

shareedit

Example:

using(SqlConnection MyConnection = new SqlConnection("Connection string"))
{
    MyConnection.Open();

    //...

    // 1. SQLConnection is a type that implements IDisposable
    // 2. So you can use MyConnection in a using statement
    // 3. When using block finishes, it calls Dispose method of 
    // SqlConnection class
    // 4. In this case, it will probably close the connection to 
    // the database and dispose MyConnection object

}

You can create your own objects that implements IDisposable:

public class MyOwnObjectThatImplementsIDisposable : IDisposable
{

    //... some code

    public void Dispose()
    {
        // Put here the code you want to be executed when the
        // using statement finish.
    }
}

So you could use an object of MyOwnObjectThanImplementsIDisposable type in a using statement:

using(MyOwnObjectThatImplementsIDisposable MyObject = new MyOwnObjectThatImplementsIDisposable)
{

 // When the statement finishes, it calls the 
 // code you´ve writed in Dispose method
 // of MyOwnObjectThatImplementsIDisposable class
}

Hope this helps

shareedit

If you want a summary rule. Anytime an object using IDisposable where you would not have a catch, use using. Using, essentially, is this pattern:

try
{
  //instantiate and use object
}
finally
{
  //dispose object
}

If you do not need a catch, using can save you typing, which is a good thing.

shareedit

In this context the using statement is handy for types that implement IDisposable. When the code block exits the scope of the using statement, Dispose() is called implicitly. It’s a good habit when working with objects you want to dispose immediately after use.

shareedit
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s