Can anyone be so kind to explain (step by step) the below peice of code I stumbled across
public static List ReadList(string procedure, Func, T> make, object[] params = null)Ive never seen anything like this using generics and Func<> delegates in this way?
From my understanding of the below method name ReadListwhich returns a generic Listwhen invoked, ReadList needs to be implemented with a specific closed type instead ofand accepts 4 input parameters, the first of type string, the second a datareader, the third a make, and fourtha list of objects that return null?
VulpesPosted Feb 1, 2012, 2:27 PM
Firstly, there is one too many right angle brackets.
Secondly, 'params' is a keyword and can't be used as the name of a parameter unless 'escaped' with an @.
If it had been written like this, then it would compile:
public static List
The method would then take three parameters:
a) A string named 'procedure'
b) A Func delegate named 'make', representing a method which takes a single parameter of type IDataReader and produces a result of type T.
c) An object array named @params which, if not present, has a default value of null.
VulpesPosted Feb 1, 2012, 4:41 PM
All I was doing was demonstrating how you would call the method and how the compiler could infer the type of T.
It will, of course, work just as well if you specify T explicitly and/or specify null for the third argument.
Guest UserPosted Feb 1, 2012, 2:58 PM
Forgive my denseness but I dont see how you have implemented ReadList
List
Should ReadList have originally been T before the implementation to ReadList?
VulpesPosted Feb 1, 2012, 2:46 PM
As there are no constraints on T, then it could be replaced by any class or struct.
The method would return a reference to a List
Also, you shouldn't need to specify T when calling the method as the compiler should be able to deduce it from the delegate return type. To take a (rather silly) example, this should compile fine:
List
As 6.0 is a double literal, the compiler should be able to figure out that T is double.
@params would, of course, be given its default value of null.
Guest UserPosted Feb 1, 2012, 2:34 PM
Could you explain how List