Comparison between "Using" and "finally"
This article is used to identify the basic difference between "Using" and "finally" in C#. It will helpful to choose the adoptable dispose method based on our requirement. As a developer we should know to dispose the object in best manner. We can dispose the object based on "Using" or "finally".
Using statement disposes out the object that is being created.
For Example :
Using(SqlConnection conn = new SqlConnection(connString))
{
//some code
}
The above code snippet is equilent to :
try
{
}
finally
{
}
1. In the finally{} block we have to manually dispose the method but the Using statement automatically disposes the object when its being created
2. Compare to try{} finally{} concept Using is good one
3. In the finally block we have to check the null condition based on the object and then disposing the object but "Using" no need to check that null conditions
4. When "Using" is converted into machine language it will be converted by CLR as mentioned below :
try
{
}
catch
{
}
5. Basically both are same but "Using" is handy one.
If you want to catch an exception thrown by the code inside the using block. We have to write the code mentioned as below:
Using(SqlConnection conn = new SqlConnection(connString))
{
try
{
}
catch
{
}
}
This code snippet will dispose the object as well as handle the exceptions.