views:

2704

answers:

6

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);
A: 

It's ugly, but you can use an out parameter. From my enum parser:

public static T Parse<T>(string value)
{
    // return a value of type T
}

public static void Parse<T>(string value, out T eValue)
{
    // do something and set the out parameter
}

// now can be called via either
SomeEnum blah = Enums.Parse<SomeEnum>("blah");

// OR
SomeEnum blah;
Enums.Parse("blah", out blah);

The second one will infer the type, but like I said, it's ugly.

Chris Doggett
Yeah, I have a similar enum parser function and I thought about that. Before I'd go down that road I'd want to compare the performance of these options. Really, this is all about convenience and readability, so in the end I'll go with whatever is fastest.
Josh
Performance-wise, I haven't seen a difference. Readability-wise, it really helped in 2.0 when I had Map/Reduce functions that used generics and fully-qualified type names. 300-character lines are a real pain to read, even if you break them into separate lines, and this let me fit the same thing on one line without having to use both monitors.
Chris Doggett
A: 

Not using generics. Type inference is a compile-time event. One solution would be to have a generic delegate as you posted. The generic delegate would be faster than a cast.

JohnOpincar
You mean the "public delegate T BorrowReader<T>(IDataReader reader);" one? Is that faster than a cast? I figured the type inference would slow it down.
Josh
Like I said, type inference is done by the compiler, casting happens at run-time.
JohnOpincar
A: 

I don't think there's a way around it. At least not in the way you propose it. The main problem being that since it has to be infered at compile time, if you don't have an explicit return type, then the compiler can't actually infer the return type.

enriquein
I'm open to other proposals. :)
Josh
+2  A: 

How about:

public static T Bar2<T>(Func<IDataReader,T> func) where T : class
{
    BorrowReader borrower = new BorrowReader(func);
    return (T) Foo.Bar(borrower);
}

I know it's still doing the cast anyway, which is ugly, but it should work. (I originally thought you could get away with an implicit conversion from func, but apparently not. At least not before C# 4.0.)

Of course, if you can change the signature of Foo.Bar to be generic, you're laughing...

EDIT: To answer the comment: if the signature of the method is changed to take a generic delegate, e.g.

public static T Bar<T>(Funct<IDataReader, T> func)

then the calling code can nearly just be:

var result = Foo.Bar(DoFooBarMagic);

Unfortunately, type inference doesn't work with method groups so you have to use either:

Func<IDataReader, List<string>> func = DoFooBarMagic;
var result = Foo.Bar(func);

or (nicer, if slightly less efficient)

var result = Foo.Bar(reader => DoFooBarMagic(reader));

So you're right - this answer didn't quite get the OP to exactly what was required, but presumably it came close enough to get acceptance. Hopefully this edit is helpful to explain the rest :)

Jon Skeet
Interesting. I'll have to play with that one a bit and see if it will work for me. I wonder what the efficiency gain/loss compared to the straight cast is.
Josh
If this is going to be talking to a database in real life, then any performance penalty of the cast is going to be insignificant.
Jon Skeet
Very true. But that doesn't mean we don't try to perfect it! :)
Josh
I missed the last statement. I can change Foo.Bar. I'll edit to add the signature.
Josh
For those of us that are slow, can we see how the call will work with this answer? I'm having trouble seeing how this helps.
JohnOpincar
For completeness: Func<IDataReader, List<string>> is the same as BorrowReader<List<string>> here, and you can also write the call as Foo.Bar<List<string>>(DoFooBarMagic)
Lucas
A: 

I can't get the accepted answer to work. No type inference occurs. What am I missing?

public delegate object BorrowReader(IDataReader reader);

public class Foo
{
    public static object Bar(BorrowReader del)
    {
     return null;
    }

    public static T Bar2<T>(Func<IDataReader, T> func) where T : class
    {
     var borrower = new BorrowReader(func); 
     return (T) Foo.Bar(borrower);
    }

    public static List<String> DoFooBarMagic(IDataReader reader)
    {
     return new List<string>();
    }

    public void Compiles()
    {
     var result = Foo.Bar2<List<string>>(Foo.DoFooBarMagic);
    }

    public void DoesNotCompile()
    {
     var result = Foo.Bar2(Foo.DoFooBarMagic);
     // The type arguments for method 'Foo.Bar2<T>(System.Func<System.Data.IDataReader,T>)' 
     // cannot be inferred from the usage. Try specifying the type arguments explicitly. 
    }
}
JohnOpincar
A: 
// if BorrowReader is generic...
public delegate T BorrowReader<T>(IDataReader reader);

public class Foo
{
    // ... and Foo.Bar() is also generic
    public static T Bar<T>(BorrowReader<T> borrower) { ... }

    public void SomeMethod()
    {
        // this does *not* work (compiler needs more help)
        var result1 = Foo.Bar(DoFooBarMagic);

        // but instead of this (which works)
        var result2 = Foo.Bar(new BorrowReader<List<string>>(DoFooBarMagic));

        // you can do this (also works)
        // which emits the same IL, anyway
        var result3 = Foo.Bar<List<string>>(DoFooBarMagic);
    }
}
Lucas
So how's that an improvement?
JohnOpincar
It doesn't give you what want "Foo.Bar(DoFooBarMagic)". Mostly I added it for completeness since nobody had suggested it yet. It's more consice than "Foo.Bar(new BorrowReader<..>(..))" and it's as good as you can get without resorting to casting.
Lucas