How can I work around C#'s limitation on calling static functions on a Generic type?

When you only need one method, think Func... perhaps a Func ToList(this DataTable table, Func converter) { IList list = new List(); foreach (DataRow row in table. Rows) list. Add(converter(row)); return list; } Then call table.

ToList(User. FromDataRow).

When you only need one method, think Func... perhaps a Func public static IList ToList(this DataTable table, Func converter) { IList list = new List(); foreach (DataRow row in table. Rows) list. Add(converter(row)); return list; } Then call table.

ToList(User. FromDataRow).

You can remove the first parameter of ToList in the example call. – JaredPar Apr 9 '09 at 20:54 It should be able to infer type T from the Func. – Samuel Apr 9 '09 at 20:57 @Samuel, I believe method groups do not participate in type inference.

– JaredPar Apr 9 '09 at 20:59 Kind of sucks that I have to pass a function, but at least it works! Thanks a ton for this :) – Stuart Branham Apr 9 '09 at 20:59 @JaredPar: I was wrong, it cannot infer the type. – Samuel Apr 9 '09 at 21:00.

In your example code, you're using a static method to create the user from the DataRow: foreach (DataRow row in table. Rows) users. Add(User.

FromDataRow(row)); But, you can't use static methods to implement an interface. Assuming that your interface looks like this: public interface IDataModel { void FromDataRow(DataRow row); } then your User class will have an instance method FromDataRow(), not a static one. If your classes have parameterless constructors, then you could write this: public static IList ToList(this DataTable table) where T : IDataModel, new() { IList results = new List(); foreach (DataRow row in table.

Rows) { T item = new T(); item. FromDataRow(row); results. Add(item); } return users; } The IDataModel constraint on requires the type to implement IDataModel.

The new() constraint on requires the type to have a parameterless constructor.

Ah yes, I wasn't thinking straight on that interface. Thanks for pointing that mistake out. This solution looks pretty swell.

I'll have to do some thinking on which route to go. FromDataRow is actually a static method. – Stuart Branham Apr 9 '09 at 21:29.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions