Hi all,
I've been looking on SO this morning to find a way of creating a List of specific objects from a System.Data.DataTable. So far, I have this in my DomainModel base class:
protected static List<T> ConvertTo<T>(DataTable dt) where T : class, new()
{
int count = dt != null ? dt.Rows.Count : 0;
List<T> list = new List<T>(count);
if (dt != null & dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
T item = new T(); // ????
FillObjectFromDataRow(item, row);
list.Add((T)item);
}
}
return list;
}
Note: I want an empty list returned, as mostly it just gets bound to datagrids, repeaters, etc., mostly.
However, it doesn't work as the classes generally have a private constructor to prevent unauthorised instantiation (I'm mean that way), so I get the "type 'typename' must be a non-abstract type with a public parameterless constructor" error.
I am loathe to introduce a public parameterless constructor to my classes as they contain 90% of static methods (which are used with ObjectDataSources) and having an "empty" class being created would not make sense. I.e. a new Employee object would be blank instead of being created by public static Employee Get(string employeeID), which would contain far more useful information.
Any ideas on how I can create a "thing" of T at the '????' marked row without using the new() constraint? Can I instantiate a "thing" via a Type parm?
Thanks for any ideas, just trying to DRY in my apps by having this...
Kind regards,
Mike K.
PS And yes, maybe the dt.Rows.Count > 0 call is unnecessary...