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

Home Forums General Programming C# What is the best use of the Using statement in .net

This topic contains 0 replies, has 2 voices, and was last updated by  Pavan 6 years, 9 months ago.

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
    Moderator

    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.