Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reducing number of using in C#

My question might be silly or may not be a question at all, but here it goes..

I am performing quite some database operations in my ASP.net MVC project where I am creating two objects each and every time namely, SqlConnection and SqlCommand.

I have shown an example below

using (SqlConnection connection = new SqlConnection(connectionString))
{
  using (SqlCommand command = new SqlCommand("sRegisterUser", connection))
  {

I am doing all these different operations inside one class under different methods.

My question is how can I reduce the creation of these objects each and every time? How can I create them globally

PS: sRegisterUser is a stored procedure, like wise other methods use different procedures which gets different values as parameters.

Please help me out.

Thanks for any help in advance.

like image 525
RandomUser Avatar asked Dec 07 '22 02:12

RandomUser


2 Answers

The answer is, don't. You do not want to share these objects, you are using them appropriately.

like image 88
Mike Perrenoud Avatar answered Dec 08 '22 14:12

Mike Perrenoud


You don't. You either keep the object alive, which is bad. Or you dispose it the way you should, and currently do.

So, why do you have use using?

Since using is necessary for disposing the handles in Windows.

You could also write this, which is similar to using using:

SqlConnection connection = new SqlConnection(connectionString);
connection.Close();
connection.Dispose();

using also disposes when the code above throws an error. Using using is actually the shortest way to code this.

So the error-save version should be:

SqlConnection connection;

try
{
    connection = new SqlConnection(connectionString);

    ...

    connection.Close();
}
finally
{
    connection.Dispose();
}
like image 32
Patrick Hofman Avatar answered Dec 08 '22 15:12

Patrick Hofman