So a using statement automatically calls the dispose method on the object that is being \"used\", when the using block is exited, right?
But when is this necessary/benef
I like to use them like this:
static public void AddSampleData(String name)
{
String CreateScript = GetScript(String.Format("SampleData_{0}", name));
using (IDbConnection MyConnection = GetConnection())
{
MyConnection.Open();
IDbCommand MyCommand = MyConnection.CreateCommand();
foreach (String SqlScriptLine in CreateScript.Split(';'))
{
String CleanedString = SqlScriptLine.Replace(";", "").Trim();
if (CleanedString.Length == 0)
continue;
MyCommand.CommandText = CleanedString;
int Result = MyCommand.ExecuteNonQuery();
}
}
}
They work great for cases where you don't want to put error checking code only cleans up and passes the error on down. The alternative method would look like this:
static public void AddSampleData(String name)
{
String CreateScript = GetScript(String.Format("SampleData_{0}", name));
IDbConnection MyConnection = null;
try
{
IDbConnection MyConnection = GetConnection();
MyConnection.Open();
IDbCommand MyCommand = MyConnection.CreateCommand();
foreach (String SqlScriptLine in CreateScript.Split(';'))
{
String CleanedString = SqlScriptLine.Replace(";", "").Trim();
if (CleanedString.Length == 0)
continue;
MyCommand.CommandText = CleanedString;
int Result = MyCommand.ExecuteNonQuery();
}
}
finally
{
if (MyConnection != null
&& MyConnection.State == ConnectionState.Open)
MyConnection.Close();
}
}
And frankly, which method is easier to read? Same thing with forms:
public void ChangeConfig()
{
using (ConfigForm MyForm = new ConfigForm())
{
DialogResult ConfigResult = MyForm.ShowDialog();
if (ConfigResult == DialogResult.OK)
SaveConfig();
}
ConfigForm MyForm = new ConfigForm();
DialogResult ConfigResult = MyForm.ShowDialog();
MyForm.Dispose();
if (ConfigResult == DialogResult.OK)
SaveConfig();
}