Is this use of using an appropriate way to dispose of resources being that a DataSet is returned in a WCF method?
public DataSet SearchName(string LastName, string FirstName, DateTime DateOfBirth)
{
try {
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.DBPreTrial))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "spSearchName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("@LastName", LastName);
cmd.Parameters.AddWithValue("@FirstName", FirstName);
cmd.Parameters.AddWithValue("@DateOfBirth", DateOfBirth);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet dtDocData = new DataSet();
da.Fill(dtDocData);
return dtDocData;
}
}
}
}
catch (Exception ex)
{
throw new FaultException("Exception - SearchName: " + LastName + ", " + FirstName + ", " + Convert.ToString(DateOfBirth) + " : " + ex.Message);
}
}
Or, is this second implementation required?
public DataSet SearchName(string LastName, string FirstName, DateTime DateOfBirth)
{
DataSet dtDocData = new DataSet();
try {
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.DBPreTrial))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "spSearchName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("@LastName", LastName);
cmd.Parameters.AddWithValue("@FirstName", FirstName);
cmd.Parameters.AddWithValue("@DateOfBirth", DateOfBirth);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dtDocData);
}
}
}
return dtDocData;
}
catch (Exception ex)
{
throw new FaultException("Exception - SearchName: " + LastName + ", " + FirstName + ", " + Convert.ToString(DateOfBirth) + " : " + ex.Message);
}
if (dtDocData != null)
{
dtDocData.Dispose();
}
}
Yes, the code provided disposes of resources correctly by utilizing the using statement for SqlConnection, SqlCommand, and SqlDataAdapter objects. The using statement ensures that these objects are disposed of properly even if an exception occurs.
The DataSet is returned without needing explicit disposal as it will be garbage collected once it goes out of scope.