Using C# 3.5 I wanted to build up a predicate to send to a where clause piece by piece. I have created a very simple Console Application to illustrate the solution that I arrived at. This works perfectly. Absolutely perfectly. But I have NO idea how or why.
public static Func<Tran, bool> GetPredicate() { Func<Tran, bool> predicate = null; predicate += t => t.Response == '00'; predicate += t => t.Amount < 100; return predicate; }
When I say ‘predicate +=’, what does that mean? predicate -= appears to do nothing and ^=, &=, *=, /= aren’t liked by the compiler.
The compiler doesn’t like ‘predicate = predicate + t => t.Response….’ either.
What have I stumbled on? I know what it does, but how does it do it?
If anyone wants to go delve into more complicated lambda’s, please do so.
‘delegate += method’ is operator for multicast delegate to combine method to delegate. In the other hand ‘delegate -= method’ is operator to remove method from delegate. It is useful for Action.
In this case, only Method1 and Method3 will run, Method2 will not run because you remove the method before invoke the delegate.
If you use multicast delegate with Func, the result will be last method.
In this case, the result will be 3, since method ‘() => 3’ is the last method added to delegate. Anyway all method will be called.
In your case, method ‘t => t.Amount < 100’ will be effective.
If you want to combine predicate, I suggest these extension methods.
Usage
EDIT: correct the name of extension methods as Keith suggest.