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 programme.(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.