What is using statement in c#?

Generally in our applications we will write code like create connection object to handle connectionstring after that open a connection and create command object etc. to interact with database to get data that would be like this


SqlConnection con = new SqlConnection(connectionString);


SqlCommand cmd = new SqlCommand (commandString, con);



It’s very easy way to write above code but problem is SqlConnection and SqlCommand objects will create IDISPOSABLE interface that means it could create unmanaged resources in our application to cleanup those objects we need to call Dispose() method at the end of our process otherwise those objects will remain in our application.

Suppose we use using statement in our applications it will automatically create try / finally blocks for the objects and automatically runs Dispose() method for us no need to create any try/finally block and no need to run any Dispose() method.

If we use using statement we need to write code will be like this


using (SqlConnection con = new SqlConnection(connectionString))


using (SqlCommand cmd = new SqlCommand (commandString, con))








Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s