What is the best use of the Using statement in .net

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #3204
    MikeJ
    Member

    Hi

    can anyone explain me what is the use of the Using statement in .net.
    please explain me with example..

    thanks

    #3210
    Pavan
    Member

    Hello MikeJ,
    Using in .Net is just like try catch and finally block. Like when we make connection with sql server then connection should be open in try block and we close the connection in finally block.
    But when we used using statement then no need to close the connection when connection object goes out of scope then it dispose connection automatically.
    Example 1:

    using(SqlConnection cn = new SqlConnection(ConfigurationManager.
    ConnectionStrings
    ["MyConnection"].ConnectionString))
    using(SqlCommand cmd = cn.CreateCommand())
    using(SqlDataAdapter sda = new SqlDataAdapter())
    { 
     cn.Open();
      /* code that actually does stuff */  
     }
    Example 2:
     Connection c;
    	try
    	{		c = new Connection(...);  	
                }
    	finally
    	{		c.Close();
    	}
    

    Thanks
    pavan

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.