C#: Using or not using

I am not referring to the using directive to import types defined in other namespaces, but I am referring to the using statement to define a scope where at the end of it an object will be disposed, such as this:

using (var cn = new SqlConnection())
{
	// your code here...
}

 

Just be aware that the using statement is just a shortcut or a convenient syntax for the below code:

var cn = new SqlConnection();
try
{
	// your code here...
}
finally
{
	if (cn != null) ((IDisposable)cn).Dispose();
}

 

And if you have a trycatch block in your method, either outside or inside the using statement, or maybe even both, then you need to make sure the flow of control and the logic when an exception occurs is what you would expect, because nested trycatch block can become confusing.  Just remember the using statement is a tryfinally block.

My point is, don’t haphazardly use using statement especially if you are using it for several objects in your method, because depending on what you are trying to achieve, sometimes its better to just use a complete trycatchfinally block to make your code simpler to understand.

EDIT:

Rule of thumb is if the resource object you are trying to use in your method needs to be disposed of by your method then using statement is best.  And make sure you are instantiating the resource object inside the using statement and not outside and passing the variable to it.  See using Statement (C# Reference).

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