Question

I'm using a delegate to hold a few methods that test a value and return a true/false result. After learning that a call to a delegate will only return the result of the last method in the delegate, I'm unsure of how to proceed.

I'd like to receive either the list of results from all the method calls in a delegate or if any of the calls returned true.

First I tried enumerating over the delegate with a foreach, which didn't work. I had to pull the methods out beforehand like so

System.Delegate[] methods = int_testers.GetInvocationList();

// Methods in int_testers returns true when a condition is met by the input value

Then enumerate with dynamic invokes on each member within 'methods'

foreach (var item in ds) {
    if ((bool)item.DynamicInvoke(4))
        return true;
}

However, I've read that DynamicInvoke is much slower (order of magnitude or more) than Invoke which is a trade off I'm not willing to make.

The alternative so far I've found is to have a list of Func<int,bool> and enumerate over those,

List<Func<int,bool>> methods = ....; // Add the methods into the list

foreach (var method in methods) {
    if(method(4)) {
        return true;
    }
}

While this works, it seems like an issue delegates were made to solve. So, finally, is there a way to get a list of results from a delegate without simulating a delegate by hand?

This is essentially using the results of a map function in functional terms but I don't have enough C# experience to bring that idea nicely to what I'm doing.

I looked into LINQ a little for this and it seems it could work with the second method I've outlined though I can't seem to use LINQ with delegates in this case.

Was it helpful?

Solution

You could use Predicate<T> instead of delegate, and LINQ's Any() instead of a for loop:

var methods = new List<Predicate<T>>();

// add methods to list

return methods.Any(x => x(4));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top