Luke Smith Write today, wrong tomorrow

Creating a generic list from a SqlDataReader

I've just been working on the data access layer for a project at work and found myself
replicating alot of very similar code when it came to looping through the SqlDataReader
and creating and populating a custom object for each IDataRecord (creating lists of
projects, staff etc). I sat back and thought "there must be an easier way to write
not much code, after all this is the world of .NET and C#".

So here's my solution for returning a a generic List<> populated from a SqlDataReader.

public interface IObjectPopulator
object Populate(IDataRecord

public class Project
: IObjectPopulator
   private int?
   public int?
      get { return _id;
      internal set
{ _id = value;

   private string _name;
   public string Name
      get { return _name;
      set { _name = value;

   #region IObjectPopulator

   public object Populate(IDataRecord
      Project project = new Project();
      project.Id = Convert.ToInt32(dr["project_ID"]);
      project.Name = Convert.ToString(dr["project_name"]);

      return project;




protected List<T>
PopulateList<T>(SqlDataReader reader)
   ArgumentValidator.CheckForNullReference(reader, "reader");
   List<T> list = null;


      list = new List<T>();

      while (reader.Read())
         object o = Activator.CreateInstance(typeof(T));
         IObjectPopulator populator = o as IObjectPopulator;

         if (populator
!= null)
            T item = (T)populator.Populate(reader);



   return list;

instead of having to loop thru the SqlDataReader in every method that creates a List<> I
can just call

projects = base.PopulateList<Project>(reader);

myself alot of lines of code.

comments powered by Disqus