Delegates as callable values
Delegates as callable values
A delegate is a type-safe callable value: it represents a compatible method and, where needed, the object on which that method runs. Pass behavior as an argument when the caller should decide an operation.
Examples target the proposed C# 14 / .NET 10 console baseline. Each is a separate Program.cs; outputs are predictions pending compilation.
Declare and invoke a delegate
Declare a delegate with its result type, name and parameters. A compatible method name without parentheses is a method group that can convert to the delegate type. Calling the resulting variable invokes the associated method. Delegate types are reference types; a nullable delegate may be absent.
using System;using System.Globalization;Adjustment discount = Reduce;Console.WriteLine(discount(80m).ToString("0.00", CultureInfo.InvariantCulture));static decimal Reduce(decimal amount) => amount * 0.75m;delegate decimal Adjustment(decimal amount);Reduce matches the delegate’s decimal input and result. The call uses the chosen method, not a hard-coded method inside the caller.
Expected output (reasoned, not executed):
60.00Pass behavior into another method
A parameter of a delegate type expresses an expected signature. The caller supplies a compatible method group or anonymous method. This is useful for a calculation policy that can vary without copying the entire algorithm. An instance method delegate also retains the target object.
using System;Console.WriteLine(Total(20, AddPickup));Console.WriteLine(Total(20, AddDelivery));static int Total(int subtotal, ShippingRule rule) => rule(subtotal);static int AddPickup(int subtotal) => subtotal;static int AddDelivery(int subtotal) => subtotal + 5;delegate int ShippingRule(int subtotal);The caller chooses the rule while Total remains independent of the specific fee.
Expected output (reasoned, not executed):
2025Combine and remove callbacks
Delegates can have invocation lists. Combining compatible delegates with += creates or extends an invocation list; it does not call any target. A later invocation runs the listed targets in order. The -= operator removes the last matching occurrence (or matching contiguous subsequence). A delegate instance is immutable; combination creates another delegate value. For a non-void multicast delegate only the last successful return value is returned to the caller, so use void callbacks when the goal is notification. An uncaught exception stops normal invocation of later targets.
using System;Notice? notify = WriteStart;notify += WriteEnd;notify?.Invoke("job");notify -= WriteStart;notify?.Invoke("next");static void WriteStart(string text) => Console.WriteLine("Start " + text);static void WriteEnd(string text) => Console.WriteLine("End " + text);delegate void Notice(string text);Both callbacks run for job; the removed callback no longer runs for next. Conditional invocation handles a null delegate.
Expected output (reasoned, not executed):
Start jobEnd jobEnd nextCommon mistakes and edge cases
Do not invoke a method when assigning its method group. Do not use dynamic invocation to bypass the type contract. Multicast return values are not automatically aggregated. Delegate invocation is synchronous unless the target or surrounding code explicitly arranges asynchronous work.
Practice and next steps
Declare delegate int Transform(int value). Create Double and AddThree methods, pass each to a helper that transforms an input, then combine two void callbacks and remove one. Test input 4 and confirm the callback order.
Next: Lambda expressions and captures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Delegates as callable values — knowledge check
Apply the lesson concepts to the following scenarios.
What does `Adjustment adjust = Reduce;` do for a compatible method?
Why accept a delegate parameter in a total calculator?
What does += do to compatible void delegates?
What result does a normally completing non-void multicast delegate expose?
What happens when a callback throws an uncaught exception during ordinary multicast invocation?