X

The using statement in C#

dotnet C#

The using statement in C# is a form of shortcut for try and finally block of code. Things to note is in order to use the using statement the object needs to implement the IDisposable interface, and using does not catch Exception, it just guarantees the call of Dispose.

Example:


try {    
  connection = new SqlConnection("");
}
finally {
  if(connection != null)
     connection.Close();
}

Can be replaced with


using(var connection = new SqlConnection(""))
{

}
 

One will not need to call the Close method of sql connection, since the dispose will do that.

Categories: .NET C#
Taswar Bhatti:
Related Post