fubo
fubo

Reputation: 46007

Combining delegates

The following code

Func<int, int> DoWork;
DoWork = x => x + 5;  // ignored
DoWork += y => y + 1; // used
Console.WriteLine(DoWork(2)); // 2 + 1 = 3

returns 3, because only the latest added lambda is being processed - the previous methods are being ignored. In case of an Action<>, all Methods are being processed.

Question: Is there a use case for "adding"/ Delegate.Combine Funcs, when the previous ones are being overwritten each time I add another delegate?

Upvotes: 0

Views: 133

Answers (1)

sloth
sloth

Reputation: 101142

The "previous ones" don't get overwritten. They all will be invoked, but only the return value of the last one is being returned.

The C# spec (15.4 Delegate invocation) explains it:

If the delegate invocation includes output parameters or a return value, their final value will come from the invocation of the last delegate in the list.


To test it, try something like:

DoWork = x => { Console.WriteLine(x + 5); return x + 5; };
DoWork += y => { Console.WriteLine(y + 1); return y + 1; };

Console.WriteLine(DoWork(2)); // 2 + 1 = 3

It will print

7
3
3

The most common use case is probably using multiple event handlers subscribing to the same event.

Upvotes: 6

Related Questions