I am a bit rusty on generics, trying to do the following, but the compiler complains:
protected List<T> PopulateCollection(DataTable dt) where T: BusinessBase { List<T> lst = new List<T>(); foreach (DataRow dr in dt.Rows) { T t = new T(dr); lst.Add(t); } return lst; }
So as you can see, i am trying to dump contents of a Table into an object (via passing a DataRow to the constructor) and then add the object to collection. it complains that T is not a type or namespace it knows about and that I can’t use where on a non-generic declaration.
Is this not possible?
There are two big problems:
PopulateCollection<T>instead ofPopulateCollection.You’ve already got a constraint that
T : BusinessBase, so to get round the first problem I suggest you add an abstract (or virtual) method inBusinessBase:Also add a parameterless constructor constraint to
T.Your method can then become:
If you’re using .NET 3.5, you can make this slightly simpler using the extension method in
DataTableExtensions:Alternatively, you could make it an extension method itself (again, assuming .NET 3.5) and pass in a function to return instances:
Your callers would then write:
This assumes you go back to having a constructor taking a
DataRow. This has the benefit of allowing you to write immutable classes (and ones which don’t have a parameterless constructor) it but does mean you can’t work generically without also having the ‘factory’ function.