skip to content

In C#, three discount rules are combined into one Func<decimal, decimal> with +=; what does invoking it return?

level: middleimportance: must knowfreq 65%

answer

  1. every target runs
  2. same argument for each
  3. earlier results discarded
  4. GetInvocationList to see all

basics

~20 s

Every rule runs in the order it was added, each with the caller's original argument, and the call returns only the last rule's result. Earlier return values are discarded; to use them, iterate GetInvocationList() and invoke each target yourself.

solid answer

~40 s

`+=` on a delegate variable calls `Delegate.Combine`, which produces a **multicast delegate** whose invocation list holds the three rules in the order they were added. Invoking it calls each target synchronously, in that order, passing every target the **same arguments** the caller supplied, and returns the **last** target's return value; the others are computed and thrown away. So a seasonal rule, a coupon and a price floor combined this way do not chain: for 100 the call returns whatever the floor rule computes from 100. To collect every result, loop over `rules.GetInvocationList()`, cast each entry to `Func<decimal, decimal>` and invoke it. To chain rules, feed each result into the next yourself or compose them; multicast is the wrong tool for a pipeline.

code

csharp · 21 lines
csharp
using System;
using System.Collections.Generic;
using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

Func<decimal, decimal> rules = price => price * 0.90m;   // seasonal 10 % off
rules += price => price - 5m;                            // coupon
rules += price => Math.Max(price, 20m);                  // price floor

Console.WriteLine(rules(100m));   // every rule runs, each on 100; only the last result comes back

var all = new List<decimal>();
foreach (Func<decimal, decimal> rule in rules.GetInvocationList())
    all.Add(rule(100m));
Console.WriteLine(string.Join(", ", all));

decimal running = 100m;                                  // chaining: feed each result to the next rule
foreach (Func<decimal, decimal> rule in rules.GetInvocationList())
    running = rule(running);
Console.WriteLine(running);

go deeper

for a junior

Remember that += on a delegate adds a target and that calling the delegate then calls every target in order.

for a middle

Explain that every target receives the same arguments, only the last return value reaches the caller, and GetInvocationList exposes each target.

for a senior

Spot multicast Func and Func<T, bool> validators in review as silent bugs, and replace them with explicit loops or composition.

for a principal

Set a codebase convention that multicast is for Action-shaped notifications only, with value-returning rules composed explicitly so the data flow is reviewable.

## What += does to a delegate variable A **multicast delegate** is a delegate whose **invocation list** holds more than one method. Every C# delegate type derives from `System.MulticastDelegate`, so any of them can become one. Writing `rules += rule` on a delegate variable compiles to `rules = (Func<decimal, decimal>)Delegate.Combine(rules, rule)`: a new delegate instance is created whose list is the old list followed by the new entry, and the variable is pointed at it. A pricing engine might build its rules like this: ```csharp Func<decimal, decimal> rules = price => price * 0.90m; // seasonal rules += price => price - 5m; // coupon rules += price => Math.Max(price, 20m); // floor ``` ## What invoking it does When `rules(100m)` runs: 1. The targets are called **synchronously, on the caller's thread, in invocation-list order** (the order of the `+=` calls). 2. Each target receives the **caller's original arguments**. The coupon rule sees `100`, not the seasonal rule's `90`. 3. The value returned to the caller is the **last target's return value**. Here the floor rule returns `Math.Max(100, 20)`, which is `100`. 4. The earlier return values (`90` and `95`) are computed and discarded. Microsoft's delegate guide states it in one line: a delegate with a return value or `out` parameters returns the return value and parameters of the last method invoked. The `ref` case is the exception to "same arguments": a `ref` argument is passed to each method in turn, so each sees the previous one's change. ## Getting every result `Delegate.GetInvocationList()` returns a `Delegate[]` holding one single-target delegate per entry, in invocation order. Iterating it lets you decide what to do with each return value: - **Collect** them into a list, as an audit view of every rule's verdict. - **Chain** them, passing each result into the next rule, which is what a discount pipeline usually means. - **Short-circuit**, stopping at the first rule that returns a sentinel. | Goal | Multicast `rules(x)` | Loop over `GetInvocationList()` | |---|---|---| | Run every target | yes | yes | | Use every return value | no, last only | yes | | Feed one result into the next | no | yes, if you pass it on | | Handle each target's exception | no | yes, with a try/catch per target | Each array entry is typed `Delegate`, so the `foreach` variable is declared as `Func<decimal, decimal>` to get a strongly typed call; the `foreach` cast does that for you. ## Why this matters in review - A validation step written as a multicast `Func<string, bool>` reports only the last check's verdict, so a failing first check is silently ignored. That is a real bug, not a style issue. - A multicast `Func` is legal but rarely intended. Most code that combines delegates uses `Action` shapes (notifications, logging), where there is no return value to lose. - If you need composition, write it explicitly; it makes the order and the data flow visible to the next reader. ## Misconceptions to retire - **"`+=` makes a pipeline."** It makes a list. Each target sees the caller's arguments, so the coupon never sees the seasonal price. - **"Only the last target runs."** All targets run, including their side effects; only the earlier return values are dropped. A logging rule earlier in the list still logs. - **"The first result wins."** The last target added wins, so the order of `+=` calls silently decides the answer. - **"Only `Action` can be multicast."** The compiler accepts `+=` on any delegate type, `Func` included, without a warning, which is exactly why the lost results go unnoticed. A short rule of thumb for reviewers: if a delegate returns a value, either it should have exactly one target, or the code should walk `GetInvocationList()` and say what happens to each result. ## In an interview State the three facts in order: every target runs, each gets the same arguments, the call returns the last result. Then show `GetInvocationList()` as the fix and mention that chaining is something you build, not something `+=` gives you.

  • What happens to an out parameter when a multicast delegate with an out parameter is invoked?
    Each target writes the `out` parameter in turn, and the caller sees the value the last target wrote, just like the return value. Earlier writes are overwritten. A `ref` parameter differs only in that each target also reads the previous target's write, so changes accumulate across the list.
  • Does a multicast delegate run its targets in parallel?
    No. Invoking a multicast delegate calls each target synchronously on the caller's thread, one after another, in invocation-list order. The call returns only after the last target finishes. If you want concurrency you have to start the work yourself, for example by iterating `GetInvocationList()` and scheduling each target.

  • Each rule receives the previous rule's result, so += builds a pipeline
  • A multicast Func returns the first target's result and skips the rest
  • Invoking a multicast Func returns an array of every target's result
  • The C# compiler rejects += on a Func because only Action can be multicast
  • The targets run in parallel, so their order is unspecified