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();
timely and efficient delivery of products and services. higher sales through better understanding of customer behaviors. cost savings from fewer staff hours and reduced human or machine error. better resource planning through detailed, accurate, and timely financial information.
Your first example is incorrect: using(var ...)
ensures that IDisposable.Dispose
is called on the variable declared inside using
upon exiting. Therefore your first example returns a disposed object, which is almost certainly wrong.
In general, the using
block is roughly equivalent to this:
var x = new MyDisposable();
try {
// Do something with x
} finally {
x.Dispose();
}
Since this is a very common pattern in C#, a special syntax is provided for your convenience.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With