Delegates in C#
What a delegate is - the definition
A delegate is a reference type that points to a method (or rather to one or more methods) - instead of storing data, it stores a reference to code that can be invoked. It is the equivalent of a function pointer from the world of C/C++, but strongly typed and safe.
You have already seen it in practice without knowing it - in RelayCommand:
public class RelayCommand : ICommand
{
private readonly Action<object> _execute; // ← to jest delegat
private readonly Predicate<object> _canExecute; // ← this is also a delegate
}
Action<object> and Predicate<object> are built-in, ready-made delegate types in .NET - for most cases you don't need to define your own.
Declaring your own delegate
// The delegate type definition - describes the SIGNATURE of the method it will point to
public delegate void OrderProcessedHandler(Order order, DateTime processedAt);
// A method matching that signature
public void LogOrderProcessed(Order order, DateTime processedAt)
{
Console.WriteLine($"Order {order.Id} processed at {processedAt}");
}
// Usage
OrderProcessedHandler handler = LogOrderProcessed;
handler(myOrder, DateTime.Now); // calls LogOrderProcessed underneath
The OrderProcessedHandler delegate can point to any method with the signature void (Order, DateTime) - the method's name doesn't matter, only the signature does.
Three built-in delegate types that cover 95% of cases
In practice, for years almost nobody has defined their own delegates (like OrderProcessedHandler above) - .NET provides generic, ready-made ones:
// Action<> - returns void, takes 0-16 parameters
Action doSomething = () => Console.WriteLine("Zrobione");
Action<string> log = message => Console.WriteLine(message);
Action<Order, DateTime> processOrder = (order, date) => { /* ... */ };
// Func<> - returns a value (the last generic parameter is the return type), 0-16 input parameters
Func<int, int, int> add = (a, b) => a + b;
Func<Order, bool> isValid = order => order.Items.Count > 0;
Func<string, Task<User>> getUserAsync = async id => await _service.GetUserAsync(id);
// Predicate<T> - a special case of Func<T, bool>, mainly for filtering/searching
Predicate<Order> hasItems = order => order.Items.Count > 0;
Predicate<T> is in practice exactly the same as Func<T, bool> - it exists mainly for historical reasons (it was in .NET before Func<> appeared) and is used in APIs such as List<T>.Find(Predicate<T>).
Multicast - a delegate can point to many methods at once
This is something a plain function pointer from C doesn't have - delegates in .NET are multicast, meaning one delegate can "hold" a list of many methods and invoke them all in turn:
Action<string> logger = null;
logger += msg => Console.WriteLine($"Console: {msg}");
logger += msg => File.AppendAllText("log.txt", msg);
logger += msg => SendToRemoteLoggingService(msg);
logger("Application started"); // calls ALL three methods in turn, in the order they were added
+= adds a method to the invocation list, -= removes it. This is, incidentally, exactly the mechanism events in C# are built on - an event is essentially a multicast delegate with restricted access (see below).
The multicast + Func<> trap: if the delegate returns a value (Func<>) and you have several methods attached, only the value from the LAST invoked method is returned - the other results are "lost". This is a common source of bugs when someone unknowingly multicasts a Func<>.
Delegate vs Event - a difference they often ask about
public class OrderProcessor
{
// A plain delegate as a field/property - ANYONE from outside can:
// - invoke it (Invoke)
// - COMPLETELY overwrite the list of handlers with =
public Action<Order> OnOrderProcessed;
// Event - restricts what can be done from outside the class
public event Action<Order> OrderProcessed;
public void Process(Order order)
{
// inside the class - both variants are allowed
OnOrderProcessed?.Invoke(order);
OrderProcessed?.Invoke(order);
}
}
var processor = new OrderProcessor();
processor.OnOrderProcessed += HandleOrder; // OK - dodanie
processor.OnOrderProcessed = null; // ⚠️ OK syntactically - someone from outside can WIPE OUT all the other subscribers!
processor.OnOrderProcessed(order); // ⚠️ OK syntactically - someone from outside can manually FIRE the event!
processor.OrderProcessed += HandleOrder; // OK - the only operation allowed from outside
processor.OrderProcessed = null; // ❌ Compile error
processor.OrderProcessed(order); // ❌ Compile error - Invoke only inside the class
event is a modifier that restricts public access to the delegate to just += and -= - from outside you can neither overwrite the whole list nor invoke it manually. This is encapsulation in its pure form - the class owns "when and whether" the event fires, and subscribers can only subscribe/unsubscribe.
Delegates as parameters - the basis of LINQ and the whole functional style in C#
This is probably the most common practical use, which you meet every day without thinking about it:
// Where przyjmuje Func<Order, bool> - delegat/predykat
var expensiveOrders = orders.Where(o => o.Total > 1000);
// Select takes a Func<Order, TResult> - a transforming delegate
var orderIds = orders.Select(o => o.Id);
// OrderBy przyjmuje Func<Order, TKey>
var sorted = orders.OrderBy(o => o.CreatedDate);
Each of these LINQ methods takes a delegate as a parameter - Where(Func<T, bool> predicate). The lambda o => o.Total > 1000 is simply a shorthand syntax for creating a delegate instance - the compiler "sees" the signature expected by Where and matches your lambda to it.
Delegates as a callback mechanism / the Strategy pattern
A classic use case - you pass "what to do" as a parameter, instead of hardcoding the logic inside the method:
public class RetryHelper
{
public static async Task<T> ExecuteWithRetryAsync<T>(
Func<Task<T>> operation, // what to execute
int maxAttempts = 3,
Action<Exception, int> onRetry = null) // what to do on every failure (optional)
{
for (int attempt = 1; attempt <= maxAttempts; attempt++)
{
try
{
return await operation();
}
catch (Exception ex) when (attempt < maxAttempts)
{
onRetry?.Invoke(ex, attempt);
await Task.Delay(TimeSpan.FromSeconds(attempt));
}
}
throw new InvalidOperationException("Should not happen");
}
}
// Usage
var user = await RetryHelper.ExecuteWithRetryAsync(
operation: () => _userService.GetUserAsync("123"),
maxAttempts: 3,
onRetry: (ex, attempt) => _logger.LogWarning($"Attempt {attempt} failed: {ex.Message}")
);
RetryHelper knows nothing about what exactly operation does - it only gets a "recipe" as a delegate and executes it according to its own retry logic. This is effectively the Strategy design pattern, implemented without creating a hierarchy of interfaces/classes - using delegates alone.
Delegates and lambda expressions - what happens "under the hood"
Func<int, int> square = x => x * x;
The compiler generates roughly:
private static int SquareLambda(int x) => x * x; // wygenerowana, "ukryta" metoda
Func<int, int> square = new Func<int, int>(SquareLambda);
So a lambda is syntactic sugar - it creates a method (static or instance, depending on whether it captures variables from the surrounding scope) and wraps it in an instance of the appropriate delegate.
Closures - a lambda can "capture" variables from the enclosing scope:
public Func<Order, bool> CreateMinTotalFilter(decimal minTotal)
{
return order => order.Total >= minTotal; // "minTotal" jest przechwycone z parametru metody
}
var filter = CreateMinTotalFilter(500m);
filter(someOrder); // "remembers" the value 500m, even though CreateMinTotalFilter finished long ago
This works because in such cases the compiler generates an additional class (a so-called closure class) that stores the captured variables as fields, and the lambda becomes a method on an instance of that class instead of an ordinary static method.
Summary - where it all comes together
ICommand/RelayCommand-Action<object>andPredicate<object>are delegates passed in the constructor, which makesRelayCommandreusable for any logic, without creating a separateICommandclass for every action in the applicationPropertyChanged/CanExecuteChanged- these are events, i.e. multicast delegates restricted (to+=/-=)- DI with
Func<T>- sometimes you injectFunc<IService>instead ofIService, when you need a factory creating a new instance on demand rather than a ready-made instance - LINQ in repositories (
Where,Select) - everywhere you filter/map collections of orders, users and so on
Delegates are, in practice, the foundation on which the whole "pass behaviour as a parameter" style in C# stands - from the simplest callback, through LINQ, to events and the entire binding system in WPF.