somethingSomething
somethingSomething

Reputation: 860

Delegate, method calls with multiple subscribers

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? enter image description here enter image description here enter image description here enter image description here

Here is the code:

    evenPredicate += someMethod;
    evenPredicate += anotherMethod;
    List<int> evenNumbers = FilterArray(numbers, evenPredicate);

Upvotes: 1

Views: 1042

Answers (2)

Marc Gravell
Marc Gravell

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

MelnikovI
MelnikovI

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

Related Questions