Hi Frank,
Of course, C# 3.0 and LINQ really open up some nice possibilities here for
what you are trying to do. But if you don't have LINQ at your disposal and
you're confined to C# 2.0, I have a few suggestions that may help.
First, for the line that won't compile. One of the best ways to get around
this is to externalize the creation of your T type by using a generic
delegate that returns a T and accepts a DataRow. The downside to this is
that for each concrete type that T could be, you need to create a method
that can create one of those concrete types from a DataRow and then wire the
method up to an instance of your generic delegate. Then you make that
delegate instance available to the DataTableToList () method so it can use it
to do the work you need in the line that won't compile. In C# 2.0, you can
simplify this syntax a bit by using anonymous methods, or not, depending on
your preference.
Additionally, I would recommend that you not actually return a List<Tfrom
DataTableToList () but rather an IEnumerable<Tin stead. Then, you can turn
your DataTableToList () method into an iterator by using a yield block. This
lazy evaluation could gain you some efficiency if one were to only iterate
through the first few items of the list because you would only be calling
the delegate mentioned in the previous paragraph for the actual items
requested rather than for the whole DataTable.
Hope this helps,
-Trey
--
-----------------------------
Trey Nash
Author of "Accelerate d C# 2008" and "Accelerate d C# 2005"
Apress
"Frank Rizzo" <no**@none.comw rote in message
news:eI******** ******@TK2MSFTN GP02.phx.gbl...
>I am trying to create a parametrized generic object, but the compiler won't
let me. Is this just the way it is? The class has a constraint that says
all classes must inherit from BusinessBase, which specifies a parametrized
constructor. But c# won't let me do it.
public class DataHelper<Twhe re T : BusinessBase, new()
{
public static List<TDataTable ToList(DataTabl e dataTable)
{
List<TlistOfIte ms = new List<T>();
foreach (DataRow dr in dataTable.Rows)
{
T recipient = new T(dr); // **** causes an error
****
listOfItems.Add (recipient);
}
return listOfItems;
}
}