I'm maintaining some C# 2.0 code and the programmer uses a pattern of reading a collection of business objects by opening a datareader and then passing it to the object's constructor. I can't see anything obviously wrong with this but it feels bad to me. Is this OK to do?
private static void GetObjects()
{
List<MyObject> objects = new List<MyObject>();
string sql = "Select ...";
SqlConnection connection = GetConnection();
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
objects.Add(new MyObject(reader));
reader.Close();
}
public MyObject(SqlDataReader reader)
{
field0 = reader.GetString(0);
field1 = reader.GetString(1);
field2 = reader.GetString(2);
}