Homde
Homde

Reputation: 4286

Generic parameter delegate?

I'm a bit fuzzy on the new Action/Func/Variance/CoVariance stuff, which is probably what I need.

What I want is to be able to pass a delegate as a parameter to a method, that takes a string and returns a bool. The problem is that I can't use a typed delegate or interface since it will be used in different libraries which doesn't share libraries, and both will be invoked by a third.

So in general I want the delegate to be inferred by it's input and returning type.

So it'll be like:

delegate bool IncludeItemDelegate(string item);

ClassA.FetchItems(int someParameter,includeItemDelegate);
ClassB.FetchItems(int someParameter,string someOtherParam,includeItemDelegate);

Where A and B doesnt share any libraries, can it be done?

Upvotes: 2

Views: 581

Answers (3)

Jonas Elfström
Jonas Elfström

Reputation: 31438

It's also possible to pass the Predicate as a lambda

class A
{
    static public IEnumerable<string> FetchItems(int max, Predicate<string> filter)
    {
        var l = new List<string>() {"test", "fest", "pest", "häst"};
        return l.FindAll(filter).Take(max);
    }
}

like this

var res = A.FetchItems(2, s => s.EndsWith("est"));

Upvotes: 0

Robert Jeppesen
Robert Jeppesen

Reputation: 7877

Predicate is built-in and also signals intent:

ClassA.FetchItems(int someParameter, Predicate<string> filter);

Upvotes: 6

leppie
leppie

Reputation: 117280

How about Func<string,bool> ?

Upvotes: 7

Related Questions