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