I'm still new to delegates, and I'm playing at the delegate-based data access level described in Stephen John Metker's book "Template Design in C #" (great reading!). It defines the data access delegate as follows:
public delegate object BorrowReader(IDataReader reader);
The result of using this code is one of the following:
var result = Foo.Bar(new BorrowReader(DoFooBarMagic)); var result = Foo.Bar(DoFooBarMagic);
However, since the return type of the delegate is an βobjectβ, you need to drop it to get what the method (DoFooBarMagic in this example) really returns. Therefore, if "DoFooBarMagic" returns a List, you need to do something like this:
var result = Foo.Bar(DoFooBarMagic) as List<string>;
I would like you to skip the broadcast and get the delegate return type from the delegate method return type. My thought was maybe a way to use the type parameter to output the return type. Something like one of them:
public delegate T BorrowReader<T>(IDataReader reader); List<string> result = Foo.Bar(new BorrowReader(DoFooBarMagic));
If the return type is inferred from the return type of the delegate method, but it does not work. Instead, you should do this:
public delegate T BorrowReader<T>(IDataReader reader); var result = Foo.Bar(new BorrowReader<List<string>>(DoFooBarMagic));
It hardly looks better than a cast.
So, is there a way to infer the return type of the delegate from the return type of the delegate method?
Edit to add: I can change the signature of Foo.Bar if necessary. The current signature is essentially this:
public static T Bar<T>(string sprocName, DbParameter[] params, BorrowReader<T> borrower);
Note: this signature is the result of the current state that this delegate definition uses:
public delegate T BorrowReader<T>(IDataReader reader);