Delegates can be combined, so:
MethodInvoker del = delegate { Console.WriteLine("Delegate 1"); };
del += delegate { Console.WriteLine("Delegate 2"); };
del.Invoke();
Outputs:
Delegate 1
Delegate 2
Since it calls both methods, I tried this to see if it would work:
Func<Person, bool> filters = person => person.Name.Contains("John");
filters += person => person.Age >= 18;
List<Person> persons = getPersons();
persons.Where(filters);
But it doesn’t, only last is applied (in this case, person => person.Age >= 18).
My question is: Why not? Is it possible to implement this? (not that I would rewrite Linq’s extension methods just to implement this, but would be cool if possible)
Note:
I know that in LINQ to Objects, doing this would be similar, as execution is deferred:
persons.Where( x => x.Name.Contains( nameFilter )).Where( x => x.Age >= 18 );
But that’s not what I’m interested in.
The reason is that both filters are executed, but only the return value of the last delegate is used. That is how delegates work according to the specification. Like the comments say, I can’t imagine how this would work differently. You’re alluding that the results should be
ANDed, but why can’t they beORed? What would happen if the results werestrings?