Explain C# delegates, events, and Func or Action with an example from a real application.
CRED · Full Stack Developer · 3-4-years · technical
Published
Year not specified · .NET, C#, Software Engineering
Community answers
Posted by wasAsked editorial collection
A delegate is a type-safe reference to a method. `Func<...>` represents a method that returns a value; `Action<...>` represents one that returns void. An event wraps a delegate with publisher/subscriber rules: outside code can subscribe or unsubscribe but cannot raise the event directly.
```csharp
public sealed record OrderPaid(Guid OrderId, decimal Amount);
public sealed class PaymentService
{
public event EventHandler<OrderPaid>? Paid;
public decimal CalculateTotal(
IEnumerable<decimal> lines, Func<decimal, decimal> discount)
{
var subtotal = lines.Sum();
return discount(subtotal);
}
public void MarkPaid(Guid id, decimal amount)
{
// Persist the payment first.
Paid?.Invoke(this, new OrderPaid(id, amount));
}
}
var service = new PaymentService();
service.Paid += (_, payment) =>
Console.WriteLine($"Receipt for {payment.OrderId}: {payment.Amount:C}");
```
Delegates are useful for strategies, callbacks, and composition. Events work for in-process notification, but they are not a durable message bus: subscribers can fail, disappear on restart, and retain objects if not unsubscribed. Use durable messaging for cross-service business events.
Pooja Parmar · · 0 likes
A delegate is a type-safe reference to a method. Func and Action are built-in generic delegate types, and events are a controlled way to expose a delegate so that other code can subscribe but not invoke or overwrite it.
Func and Action
- Action<T1,...> represents a method that returns void.
- Func<T1,...,TResult> represents a method that returns a value.
- Predicate<T> is equivalent to Func<T,bool>.
Real-world example — a pricing engine with pluggable discount rules:
public sealed class PricingService(IEnumerable<Func<Order, decimal>> discountRules)
{
public decimal Total(Order order) =>
order.Subtotal - discountRules.Sum(rule => rule(order));
}
Func<Order, decimal> festiveSale = o => o.Subtotal > 2000 ? 200 : 0;
LINQ itself is built on this idea: Where takes a Func<T,bool>.
Events — publish/subscribe inside one process:
public sealed class PaymentProcessor
{
public event EventHandler<PaymentCompletedEventArgs>? PaymentCompleted;
public void Complete(Payment p)
{
// ... business logic
PaymentCompleted?.Invoke(this, new PaymentCompletedEventArgs(p.Id));
}
}
processor.PaymentCompleted += (_, e) => emailService.SendReceipt(e.PaymentId);
The event keyword means outside code can only use += and -=; it cannot raise the event or replace the subscriber list.
Points that show experience:
- Unsubscribe (-=) when a short-lived object subscribes to a long-lived publisher, or you create a memory leak.
- Multicast delegates call subscribers in order; an exception in one stops the rest.
- Async event handlers (async void) cannot be awaited and swallow errors from the publisher's point of view; for async workflows prefer an explicit interface, a mediator or a message queue.
- For communication between services, events in C# are not enough — use a message broker.