tags:

views:

913

answers:

4

Can I pass a method with an out parameter as a Func?

public IList<Foo> FindForBar(string bar, out int count) { }

// somewhere else
public IList<T> Find(Func<string, int, List<T>> listFunction) { }

Func needs a type so out won't compile there, and calling listFunction requires an int and won't allow an out in.

Is there a way to do this?

+4  A: 

Why not create a class to encapsulate the results?

public class Result
{
     public IList<Foo> List { get; set; }
     public Int32 Count { get; set; }
}
ChaosPandion
A: 

You could wrap it in a lambda/delegate/function/method that exposed the right interface and called FindForBar, but I suspect that FindForBar has count as an out parameter as a reason, so you'd need to be sure throwing that information away was ok/safe/desirable/had the right results (you'd need to be sure of this even if you could just directly pass in FindForBar).

Logan Capaldo
+16  A: 

ref and out are not part of the type parameter definition so you can't use the built-in Func delegate to pass ref and out arguments. Of course, you can declare your own delegate if you want:

delegate V Func<T,U,V>(T input, out U output);
Mehrdad Afshari
A: 

IList implements a Count property, problem solved? Unless the count you are looking for is not the count from the list.

Norman H