I'm still new to delegates and I've been playing with the Delegate-based Data Access Layer described in Steven John Metsker's "Design Patterns in C#" book (an excellent read!). It defines the data access delegate like this:
public delegate object BorrowReader(IDataReader reader);
The result of using this is code that looks like one of these:
var result = Foo.Bar(new BorrowReader(DoFooBarMagic));
var result = Foo.Bar(DoFooBarMagic);
However, since the delegate's return type is "object", you need to cast to get whatever the method ("DoFooBarMagic" in this example) really returns. So if "DoFooBarMagic" returns List, you'd need to do something like this:
var result = Foo.Bar(DoFooBarMagic) as List<string>;
What I'd like is to be able to skip the cast and have the return type of the delegate inferred from the return type of the delegate method. My thought was maybe there's a way to use a Type parameter to inference the return type. Something like one of these:
public delegate T BorrowReader<T>(IDataReader reader);
List<string> result = Foo.Bar(new BorrowReader(DoFooBarMagic));
//Look, Ma, no cast!
var result2 = Foo.Bar(DoFooBarMagic);
Where the type of the return is inferred from the return type of the delegate method, but that appears not to work. Instead you have to do this:
public delegate T BorrowReader<T>(IDataReader reader);
var result = Foo.Bar(new BorrowReader<List<string>>(DoFooBarMagic));
Which hardly seems better than the 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 need be. The current signature is essentially this:
public static T Bar<T>(string sprocName,
DbParameter[] params,
BorrowReader<T> borrower);
Note: that signature is the result of the current state, which is using this delegate definition:
public delegate T BorrowReader<T>(IDataReader reader);