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.
Func<T, bool>delegates cause them to AND one another? I highly doubt it. Remember that you're actually returning values from these two delegates. I presume everything before the last return value in the invocation list gets discarded.Func<Person, bool> And(Func<Person, bool> a, Func<Person, bool> b) { return (Person p) => a(p) && b(p); }