Can anyone be so kind to explain (step by step) the below peice of code I stumbled across
Code
public static List ReadList(string procedure, Func, T>Code
make, object[] params = null)Code
Ive never seen anything like this using generics and Func<> delegates inCode
this way?
From my understanding of the below method name ReadList which returns aCode
generic List when invoked, ReadList needs to be implemented with aCode
specific closed type instead of and accepts 4 input parameters, theCode
first of type string, the second a datareader, the third a make, and fourthCode
a list of objects that return null?
VulpesRank #55 · 29.2K reputationPosted Feb 1, 2012, 9:27 AM EST
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.
Guest UserRank #4,868 · 321 reputationPosted Feb 1, 2012, 9:34 AM EST
Could you explain how List
VulpesRank #55 · 29.2K reputationPosted Feb 1, 2012, 9:46 AM EST
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 UserRank #4,868 · 321 reputationPosted Feb 1, 2012, 9:58 AM EST
Forgive my denseness but I dont see how you have implemented ReadList
List
Should ReadList have originally been T before the implementation to ReadList?
VulpesRank #55 · 29.2K reputationPosted Feb 1, 2012, 11:41 AM EST
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.