In C#, a pricing engine copies its rules delegate into a local, then adds a rule with +=; why doesn't the copy run it?
answer
- delegates never change
- Combine returns a new instance
- the variable is reassigned
- -= removes the right-most match
- empty list means null
basics
~20 sDelegates are immutable: += compiles to Delegate.Combine, which builds a new delegate with a longer invocation list and assigns it to the variable. The copy still references the old instance, so it keeps the old list.
solid answer
~30 sA C# delegate instance never changes after it is created. `rules += coupon` compiles to `rules = (Func<decimal, decimal>)Delegate.Combine(rules, coupon)`, which allocates a **new** delegate whose invocation list is the old one plus `coupon`, and reassigns only the variable `rules`. A local `snapshot` taken earlier still points at the old instance with the old list. `-=` works the same way through `Delegate.Remove`: it returns a new delegate without the right-most matching entry, the same delegate when nothing matches, and `null` when the list becomes empty, so calling `rules(price)` afterwards throws `NullReferenceException` while `rules?.Invoke(price)` does not.
code
csharp · 23 linesusing System;
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
Func<decimal, decimal> coupon = Rules.Coupon;
Func<decimal, decimal>? rules = Rules.Seasonal;
Func<decimal, decimal> snapshot = rules; // copies the reference to the current instance
rules += coupon; // rules = Delegate.Combine(rules, coupon): a new instance
Console.WriteLine($"{snapshot.GetInvocationList().Length} vs {rules.GetInvocationList().Length}");
Console.WriteLine(ReferenceEquals(snapshot, rules));
rules -= coupon; // removes the right-most matching entry
rules -= Rules.Seasonal; // an equal delegate (same method, same target) matches
Console.WriteLine(rules is null); // an empty invocation list is null
Console.WriteLine(rules?.Invoke(100m) ?? 100m); // rules(100m) would throw NullReferenceException
static class Rules
{
public static decimal Seasonal(decimal price) => price * 0.90m;
public static decimal Coupon(decimal price) => price - 5m;
}go deeper
Recall that += adds a method to a delegate variable, -= removes one, and a delegate variable can become null after the last removal.
Explain that delegates are immutable, that += and -= reassign the variable through Combine and Remove, and the right-most and null rules for removal.
Catch snapshot bugs where a component holds an old delegate instance, and guard calls on variables that can empty out with ?.Invoke and a nullable declaration.
Prefer an explicit list of rules over a growing multicast delegate when order, removal and inspection matter, and reserve += for simple notification lists.
## Delegates are immutable values behind a reference A **delegate** is a reference type, so assigning one variable to another copies the **reference**, not the delegate. What makes delegates unusual is that the object behind the reference is **immutable**: its target, its method and its **invocation list** (the methods a multicast delegate calls) never change after construction. Every operation that looks like a mutation creates a new delegate instead. ## What += and -= really compile to - `rules += coupon` becomes `rules = (Func<decimal, decimal>)Delegate.Combine(rules, coupon)`. `Combine` returns a new instance whose list is `rules`' list followed by `coupon`'s. If either operand is `null`, it returns the other one, which is why `+=` on a `null` variable simply stores the new delegate. - `rules -= coupon` becomes `rules = (Func<decimal, decimal>)Delegate.Remove(rules, coupon)`. `Remove` returns a new instance with the entries removed. Only the variable on the left of `+=` or `-=` is reassigned. Any other variable, field or collection slot that held the old reference keeps it. ```csharp Func<decimal, decimal> snapshot = rules; // same instance rules += coupon; // rules now points at a new instance // snapshot still has the old invocation list ``` ## The removal rules The rules for `-=` (and `Delegate.Remove`) are precise: 1. If the right operand's invocation list appears as a **contiguous sublist** of the left operand's list, those entries are removed. If it appears more than once, the **right-most** occurrence is removed. 2. If it does not appear, the result is the **left operand unchanged**; removing a delegate that was never added is not an error. 3. If removal leaves the list **empty**, the result is **`null`**. 4. If the left operand is `null`, the result is `null`; if the right operand is `null`, the result is the left operand. Entries are matched by **delegate equality**: same method and same target object. Two conversions of the same static method group are equal, so `rules -= Rules.Seasonal` removes an entry added as `Rules.Seasonal`. Two separately written lambdas with identical bodies are not equal, which is the root of handler leaks covered with event subscriptions. | Starting list | Operation | Result | |---|---|---| | A, B, A | `-= A` | A, B (right-most A removed) | | A, B, A, B | `-= (A + B)` | A, B (right-most A, B pair removed) | | A, B | `-= (B + A)` | A, B (not a contiguous sublist, unchanged) | | A | `-= A` | `null` | ## Invoke vs ?.Invoke Because an emptied delegate variable is `null`, the call syntax matters: - `rules(price)` and `rules.Invoke(price)` throw **`NullReferenceException`** when `rules` is `null`. - `rules?.Invoke(price)` evaluates to `null` instead of calling, so a value-returning delegate gives a nullable result that you can default with `??`. - With nullable reference types enabled, declare a variable that can empty out as `Func<decimal, decimal>?` so the compiler flags unguarded calls. The same immutability is what lets a publisher take a local copy of a delegate field before invoking it; that idiom and its threading story are covered with the event pattern. ## Misconceptions to retire - **"`+=` appends in place."** It never does; even when the runtime can reuse internal storage, the variable receives a different delegate instance and the old instance's invocation list is unchanged. - **"`-=` removes all copies."** It removes one occurrence, the right-most; `Delegate.RemoveAll` removes them all. - **"An emptied delegate is a no-op."** It is `null`, and a direct call throws. - **"Removing something absent throws."** It returns the left operand unchanged, silently. ## Consequences in review - A component that captured the delegate at construction time will never see rules added later. Pass the owning object, or read the current value each time, if later additions must apply. - When rules must be inspected, reordered or removed individually, a `List<Func<decimal, decimal>>` is often clearer than one growing multicast delegate, and it makes the order explicit. - `-=` that silently does nothing usually means the entry was a different delegate instance, typically a second lambda, rather than a bug in `Remove`.
- How do you remove every occurrence of a target from a delegate, not just the right-most one?Call `Delegate.RemoveAll(source, value)`. It repeats `Delegate.Remove` until the result stops changing, so every occurrence of `value`'s invocation list is removed. The C# `-=` operator always maps to `Delegate.Remove`, which removes one occurrence per call.
- Are two delegates created from the same instance method on the same object equal, and does that matter for -=?Yes. Delegate equality compares the method and the target object, not the instance, so two separate conversions of `rules.Coupon` on the same object are `==` though not reference-equal, and `-= rules.Coupon` removes an entry added earlier. The same method on a different object is a different delegate and is not removed.
- += appends the new method to the existing delegate object in place
- -= removes every occurrence of the method from the invocation list
- Removing the last entry leaves an empty delegate that does nothing when called
- -= throws when the delegate being removed was never added
- Two lambdas with identical bodies are equal, so -= with a new lambda removes the old one