Search This Blog

Saturday, March 29, 2014

The using Keyword/Statement in C# and VB.Net

All About using Keyword/Statement in C# and VB.Net

In C#,  using Keyword  can be used in two different ways and are hence referred to differently.
 As a Directive 
In  this usage, the "using" keyword can be used to include a namespace  in your program.(Mostly used)
As a Statement
Using 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 sqlconnection= new SqlConnection(connectionString) )
            {
              SqlCommand cmd = new SqlCommand(commandString, sqlconnection);
          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.

Using Statement in VB.Net

Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.
Managed resources are disposed of by the .NET Framework garbage collector (GC) without any extra coding on your part. You do not need a Using block for managed resources. However, you can still use a Using block to force the disposal of a managed resource instead of waiting for the garbage collector.
Using block has three parts: acquisition, usage, and disposal.
  • Acquisition means creating a variable and initializing it to refer to the system resource. The Using statement can acquire one or more resources, or you can acquire exactly one resource before entering the block and supply it to the Using statement. If you supply resourceexpression, you must acquire the resource before passing control to the Using statement.
  • Usage means accessing the resources and performing actions with them. The statements between Using and End Using represent the usage of the resources.
  • Disposal means calling the Dispose method on the object in resourcename. This allows the object to cleanly terminate its resources. The End Using statement disposes of the resources under the Using block's control.
How using statement works in VB.Net

Using block behaves like a Try...Finally construction in which the Try block uses the resources and the Finally block disposes of them. Because of this, the Using block guarantees disposal of the resources, no matter how you exit the block. This is true even in the case of an unhandled exception, except for a StackOverflowException.
The scope of every resource variable acquired by the Using statement is limited to the Using block.
If you specify more than one system resource in the Using statement, the effect is the same as if you nested Using blocks one within another.
If resourcename is Nothing, no call to Dispose is made, and no exception is thrown.
Example
The following example creates a file that is named log.txt and writes two lines of text to the file. The example also reads that same file and displays the lines of text.
Because the TextWriter and TextReader classes implement the IDisposable interface, the code can use Using statements to ensure that the file is correctly closed after the write and read operations.
Private Sub WriteToFile()
    Using writer As System.IO.TextWriter = System.IO.File.CreateText("myfile.txt")
        writer.WriteLine("This is line one.")
        writer.WriteLine("This is line two.")
    End Using 
End Sub 

Private Sub ReadFromFile()
    Using reader As System.IO.TextReader = System.IO.File.OpenText("log.txt")
        Dim line As String

        line = reader.ReadLine()
        Do Until line Is Nothing
            Console.WriteLine(line)
            line = reader.ReadLine()
        Loop 
    End Using 
End Sub

No comments:

Post a Comment