I am developing an application in which for each method or event I used to write whole code in try…catch…finally block.Here is the structure of the code that I used to write.
//Some Declarations
DataTable dt = new DataTable()
try
{
//Some code
}
Catch
{
}
Finally
{
dt = null;
}
This is how I used to write my code. My question is I am using datatable in try clause only. So is it necessary to dispose dt in the finally clause. Because I taught to do like this. But as far as my knowledge concern, if I declare dt in try clause, it will automatically disposed and set to null once the scope of try is over. So which one is better method?
Thanks in advance…
If the datatable is declared in the try or before your try block it will not be “disposed”. Disposing an object is usually in relation to the IDisposable interface and using statements. Some objects do need to be disposed because they use resources in the background (Like a Sql Connection). I do not see any reason why this would need to be done to the datatable.
Additionally, I see no point in setting your dt to null in your finally block, it will not speed up garbage collection or close any other resources by doing that.
See this other Stack overflow question…. Should I Dispose() DataSet and DataTable?