Thursday, 20 June 2013

"using" keyword in C#"

Two ways to use "using" keyword in C#"

In C#,  using Keyword  can be used in two different ways and are hence referred to differently.
  1. As a Directive In  this usage, the "using" keyword can be used to include a namespace  in your programme.(Mostly used).
  2. As a StatementUsing can also be used in a block of code to dispose a IDisposable objects.(less used).
Example
A simple and straightforward  approach to connect to a database server and read data would be-


SqlConnection sqlconnection = new SqlConnection(connectionString);
SqlDataReader reader = null;
SqlCommand cmd = new SqlCommand(commandString.  sqlconnection);
sqlconnection .Open();
reader = cmd.ExecuteReader();
     while (reader.Read())
       {
         //Do
       }
reader.Close();
sqlconnection .Close(); 

However, the above given code may generate error.

If any exception occurs inside while block it throws exception the connection.close() process will not executed due to the exception.To avoid this situation, we can take the help of the try....catch... finally block   by closing the connection inside the finally block or inside the catch block.

"Using" keyword takes the parameter of type IDisposable.Whenever you are using any IDisposable type object you should use the "using" keyword  to handle automatically when it should close or dispose. Internally using keyword calls the Dispose() method to dispose the IDisposable object.

So the correct code would be 
    using(SqlConnection sqlconnectionnew SqlConnection(connectionString))
            {
          SqlCommand cmd = new SqlCommand(commandStringsqlconnection);
          sqlconnection.Open();
             using (SqlDataReader reader = cmd.ExecuteReader())
             {
                while (reader.Read())
                {
                  //DO
                }
             }
           }

In this code  if any exception occurs then dispose() will be called and connection will closed automatically.

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives