I want to understand the difference between
public DataTable ExectNonActQuery(string spname, SqlCommand command)
{
using (DataTable dt = new DataTable())
{
cmd = command;
cmd.Connection = GetConnection();
cmd.CommandText = spname;
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(dt);
return (dt);
}
}
and
public DataTable ExectNonActQuery(string spname, SqlCommand command)
{
DataTable dt = new DataTable();
cmd = command;
cmd.Connection = GetConnection();
cmd.CommandText = spname;
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(dt);
return (dt);
}
}
I actually want to understand what is the benefit of creating a new object using “using” instead of creating it directly like this
DataTable dt = new DataTable();
usingguarantees that the object is disposed at the end of the using statementyou could call .Dispose() manually instead, but with
using, it will be disposed even if you throw an exceptionAnd you are protected from your own mistakes, such as forgetting to call .Dispose, or reassigning the variable before calling Dispose on it.
It’s all in the documentation:
http://msdn.microsoft.com/en-us/library/yh598w02.aspx
Edit: also, as dasblinkenlight explains in the other answer, disposing an object as you return it from a function is a bad idea
However, in the special case of DataTable, DataSet and DataView you do not really need to dispose those objects anyway, so in this particular example it is safe to ignore that DataTable is an IDisposable.
Moreover, since DataTable’s .Dispose() method explicitely does nothing (Finalization is suppressed) your first example should actually work despite returning a disposed object.
See Should I Dispose() DataSet and DataTable?
So in your particular example the practical differences are probably zero.
It is still generally good practise to wrap IDisposables with Using statement wherever practical. (if an object has to be constructed inside a function and then accessed outside that function this is not possible.)