If i have some code like this and an error occurs in the second using statement, will the dispose method on 1st using not be called?
using (System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(cnstr))
{
cn.Open();
using (SqlTransaction tran = cn.BeginTransaction(IsolationLevel.Serializable))
{
–EDIT–
Also is it better to write Try / Finally block or using statement. Internally compilter will generate Try / Finally for using statement but as per coding standards which one is better?
No, both will be called. Just because an exception is called in the inner statement, doesn’t mean that the first is ignored.
a using statement is just another syntax for:
so in your example:
Now what should be noted and what you have to be careful about is that whatever caused the first exception could cause problems with the outer using statement when it calls
Dispose(). The exception could throw the (really either) object into a faulted state and calling Dispose might result in another different exception which “masks” the first one. This is a gotcha in WFC when usingusingstatements: http://msdn.microsoft.com/en-us/library/aa355056.aspx