Reputation: 860
I'm learning C and C#, and my question is for C#. What happens if I pass a delegate as a parameter for a method, but the delegate has multiple subscribers?
Here is the code:
evenPredicate += someMethod;
evenPredicate += anotherMethod;
List<int> evenNumbers = FilterArray(numbers, evenPredicate);
Upvotes: 1
Views: 1042
Reputation: 1064014
The return value of a delegate with multiple subscribers is the return value of the last item; you can casually (not formally) verify this:
Func<int> x = () => { Console.WriteLine("1"); return 1; };
x += () => { Console.WriteLine("2"); return 2; };
int y = x(); // 2
Note that all the subscribers were invoked, though. Simply: most of the results were discarded. If an implementation so wishes, they can get the individual subscribers using GetInvocationList()
, to process the results individually, but usually in this type of scenario it is reasonable to assume a predicate acts as though it is a single subscriber.
Upvotes: 3
Reputation: 1045
It is bad practice to use return value from multicast delegate. Most possible that you will get value, returned from last attached delegate instance.
When you assign delegate instance to delegate with '=' as in you example, you just remove all attached instanced and add new. Use '+=' operatop to attach another one.
Upvotes: 2