I really want to get this out of my head. Please see below code:
using (DataTable resultTable = DBUtility.GetSingleDBTableResult(connectionString, "SELECT * FROM MyDBTable")) {
List<string> resultsList = new List<string>();
foreach (DataRow dataRow in resultTable.Rows) {
resultsList.Add(dataRow[0].ToString());
}
return resultsList;
}
Is the datatable disposed? Can someone explain how this is translated to a try/catch/finally block? MSDN states that if an exception occurred, the Dispose method will still be called but what about the return statement?
Or should i just use below code:
List<string> resultsList = new List<string>();
using (DataTable resultTable = DBUtility.GetSingleDBTableResult(connectionString, "SELECT * FROM MyDBTable")) {
foreach (DataRow dataRow in resultTable.Rows) {
resultsList.Add(dataRow[0].ToString());
}
}
return resultsList;
Probably, the second one should be used but I just need enlightenment :). Please explain. Thanks.
usingstatement is just syntactic sugar and it gets translated into try/finally block. Starting with your code, here’s how the C# compiler will translate theusingblock into try/finally block.As you can see from the code, the resultTable gets disposed for sure regardless of the return statement. The using block only makes sure that object gets disposed after the scope.
Your first code looks ok to me and need not be changed.