Monday, 4 June 2012

How to use Using block and Why to use Using block?


Yes, using stament simplifies the code for usage of an object with proper implementation. Using block automatically generates(impliments) the code to reuse an object and dispose the object.Which is done with the help of CLR(Common Language Runtime) which generates try and finally blocks at runtime implicitly. So using statement/block accepts only types which impliments IDisposable interface.
Syntax:
  using (resource)
            {
                // resource to use
            }
Using statement is used to create an object which impliments IDisposable interface.
Ex: SqlConnection, SqlDataReader,…ect such types impliement the IDisposable interface
which helps CLR implements the mechanism to implement the try{resue the object} and finally {dispose the object} blocks implictly.

We can Create objects which impliments IDisposable in 2 ways

String str=”uid=sa;pwd=”password”;database=sampledb”;

1st way
  SqlConnection conss = new SqlConnection();
            try
            {
              conss.ConnectionString=str;
            }
            finally
            {
                conss.Dispose(); // Programmer disposing the objects.

            }
2nd way
using (SqlConnection con = new SqlConnection())
            {

            }

Both are equal.
so IDisposable provides a way to programmers to dispose the objects(managed & unmanaged) objects. mainly unmanaged objects disposing Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.so which can be using block or try and finally blocks Explict Resource Cleanup.




So the type is managed type which has to impliment IDispose interface,and destory/despose in try{} and finally{} blocks for Explict Resource cleanup.


No comments:

Post a Comment